2011-08-30 42 views

回答

3

如果你想知道要緊高度一些寬度您可以使用下面的代碼:

NSString *yourString = @"My great text o0"; 
CGSize s = [yourString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; 
// s.height is your your height 

欲瞭解更多信息,請閱讀here

+0

你好,我可以加上O0文本框的位置按鈕?任何想法? –

+0

以編程方式計算其在視圖上的位置,然後添加具有自定義樣式和清除背景的UIButton。把它放在「o0」上。 – Nekto

+0

請給我代碼我如何計算視圖上的位置?任何想法? –

5

試試這個

NSString *sample = @"..."; 

CGSize txtSz = [sample sizeWithFont:[UIFont fontWithName: @"Helvetica" size: 16]]; 

CGRect lblFrame = CGRectMake(10,50, txtSz.width, txtSz.height); 

yourLabel.frame = lblFrame; 
20
label.text = @"some text of random length"; 
[label sizeToFit]; 

如果文本可能超過1行,請在調用sizeToFit之前添加label.numberOfLines = 0;;

+0

謝謝大家,sizeToFit剛剛解決我的問題:我只是在第二次按下按鈕的時候纔將標籤放在正確的位置 –

+0

非常感謝! –

3

這是2016年和sizeWithFont已經走了。

現在,在斯威夫特3,用途:

let text = "Random Text" 
let size = (text as NSString).size(attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 50)]) 
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
+0

感謝您展示如何做到這一點,但作爲NSString的文本部分涉及到我。有更多的「原生」快速的方式來做到這一點? – Gattster

+0

不是我所知道的..在未來希望NSString將完全橋接到字符串。 –