我有:的UILabel SETFRAME不调整大小的标签,即使是在layoutSubviews
#import "CustomTableViewCell.h"
@interface CustomTableViewCell()
@property (assign) CGRect titleFrame;
@property (assign) CGRect detailFrame;
@end
@implementation CustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
if (self.title != nil) {
self.titleFrame = self.title.frame;
}
if (self.detail != nil) {
self.detailFrame = self.detail.frame;
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void) setTitleTo: (NSString *)text {
if (self.title == nil || text == nil) {
return;
}
CGSize maximumLabelSize = CGSizeMake(self.title.frame.size.width, FLT_MAX);
CGRect expectedLabelSize = [text boundingRectWithSize:maximumLabelSize
options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:self.title.font}
context:nil];
CGRect newFrame = self.title.frame;
newFrame.size.height = expectedLabelSize.size.height;
self.titleFrame = newFrame;
self.detail.lineBreakMode = NSLineBreakByWordWrapping;
self.detail.numberOfLines = 3;
[self.title setText:text];
[self setNeedsLayout];
}
- (void) setDetailTo: (NSString *)text {
if (self.detail == nil || text == nil) {
return;
}
CGSize maximumLabelSize = CGSizeMake(self.detail.frame.size.width, FLT_MAX);
CGRect expectedLabelSize = [text boundingRectWithSize:maximumLabelSize
options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:self.title.font}
context:nil];
CGRect newFrame = self.detail.frame;
newFrame.size.height = expectedLabelSize.size.height;
self.detailFrame = newFrame;
self.detail.lineBreakMode = NSLineBreakByWordWrapping;
self.detail.numberOfLines = 3;
[self.detail setText:text];
[self setNeedsLayout];
}
- (void) layoutSubviews {
[super layoutSubviews];
if (self.title != nil) {
NSLog(@"T: %@", self.title.text);
[self.title setFrame:self.titleFrame];
}
if (self.detail != nil) {
NSLog(@"D: %@", self.detail.text);
[self.detail setFrame:self.detailFrame];
}
}
@end
从我正在读here它应该调整到适合文本。
和NSLog的输出:
2014-10-08 20:48:29.474 Test[57397:613] T: Largest Metro
2014-10-08 20:48:29.475 Test[57397:613] D: Oahu metropolitan area
我的理解是“瓦胡岛首都圈”应与第二行“区域”是可见的。
您会考虑使用自动布局而不是手动计算帧吗? – 2014-10-10 04:16:39
@ KenKuan-我正在慢慢转换它,因为我键入。试图准确了解约束如何在途中:) – Justin808 2014-10-10 04:25:04