[英]How to estimate the proper height of a UITextField, to hold text of given font size
我想使用UITextField顯示單行文本字段,我需要在顯示它之前知道它包含UICollectionViewCell的正確大小。 文本可以是多種字體大小之一,我需要獲得正確的高度以便舒適地顯示它。
由於文本事先不知道(它可以由用戶編輯),我不能使用NSAttributedString
的-size
和-boundingRectWithSize:options:context:
除了虛擬文本之外的任何東西,在這種情況下我不能真的相信最終的大小可以容納任何文本,對吧?
我想我的問題是:是否有關於排版的一般經驗法則,或者我不知道的一些有用的API,這將允許我確定在X
pt顯示文本,我需要一個高度的文本字段Y
px。
UITextField
實現sizeThatFits:
方法。 因此,獲得文本字段大小的最可靠方法是實際創建一個,設置它就像設置真實文本字段一樣,並要求它獲得合適的大小。 你甚至不必給它占位符文本,因為UITextField
將根據其字體而不是文本來選擇大小。
UITextField *dummy = [[UITextField alloc] init];
dummy.font = [UIFont systemFontOfSize:20];
dummy.borderStyle = UITextBorderStyleRoundedRect;
CGFloat requiredHeight = [dummy sizeThatFits:CGSizeMake(HUGE_VALF, HUGE_VALF)].height;
// requiredHeight == 30 in my test
如果您的部署目標是iOS 6.0或更高版本,則可以改為使用intrinsicContentSize
屬性,如下所示:
CGFloat requiredHeight = dummy.intrinsicContentSize.height;
// requiredHeight == 30 in my test
請注意, sizeThatFits:
仍可在iOS 6中運行,但intrinsicContentSize
更容易理解。
當borderStyle為RoundedRect時,iOS總是返回30個單位的高度。 如果要計算自定義字體所需的高度,則必須將borderStyle更改為任何其他值,計算高度,然后更改borderStyle。
textField.borderStyle = UITextBorderStyle.None;
let sizeThatFits = textField.sizeThatFits(CGSize(width:textField.bounds.width, height: CGFloat.max));
textField.bounds.height = sizeThatFits.height;
textField.borderStyle = UITextBorderStyle.RoundedRect;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.