3 回答

TA貢獻1829條經驗 獲得超13個贊
在大多數情況下,Matt的解決方案按預期工作。但如果它不適合你,請進一步閱讀。
要使標簽自動調整高度,您需要執行以下操作:
設置標簽的布局約束
設置低優先級的高度約束。它應該低于ContentCompressionResistancePriority
設置numberOfLines = 0
將ContentHuggingPriority設置為高于label的高度優先級
為label選擇preferredMaxLayoutWidth。標簽使用該值來計算其高度
例如:
self.descriptionLabel = [[UILabel alloc] init];
self.descriptionLabel.numberOfLines = 0;
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.preferredMaxLayoutWidth = 200;
[self.descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.descriptionLabel];
NSArray* constrs = [NSLayoutConstraint constraintsWithVisualFormat:@"|-8-[descriptionLabel_]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)];
[self addConstraints:constrs];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[descriptionLabel_]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
[self.descriptionLabel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[descriptionLabel_(220@300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
使用Interface Builder
設置四個約束。高度約束是強制性的。
然后轉到標簽的屬性檢查器并將行數設置為0。
轉到標簽的大小檢查器并增加垂直ContentHuggingPriority和垂直ContentCompressionResistancePriority。
選擇并編輯高度約束。
并降低高度約束優先級。
請享用。:)

TA貢獻1828條經驗 獲得超13個贊
在iOS 6中,使用自動布局,如果UILabel的邊(或寬度)和頂部被固定,它將自動垂直增長和縮小以適合其內容,完全沒有代碼,也沒有解除其抗壓性等問題。這很簡單。
在更復雜的情況下,只需設置標簽即可preferredMaxLayoutWidth
。
無論哪種方式,正確的事情都會自動發生。

TA貢獻1865條經驗 獲得超7個贊
在IOS7中注意到sizeToFit也不起作用 - 也許解決方案也可能對你有所幫助
[textView sizeToFit];[textView layoutIfNeeded];
- 3 回答
- 0 關注
- 906 瀏覽
添加回答
舉報