我使用以下代码在IOS中添加文本
//Set up label frame
UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 10, 210, 80)];
self.answer_text_label = tempLabel;
[tempLabel release];
[self.preview_answer_container addSubview:self.answer_text_label];
//Populate label with text
self.answer_text_label.text = self.answer.text;
self.answer_text_label.numberOfLines = 4;
self.answer_text_label.lineBreakMode = UILineBreakModeWordWrap;
[self.answer_text_label sizeToFit];
然而,我得到的结果就是这样,文本似乎溢出到右边,而不是按照我的标签设置'CGRectMake(100,10,210,80)'
中的规定保留在框架内
如果我更改为self.answer_text_label.numberOfLines = 0
,则包装有效。但这对我不起作用,因为我需要在规定的标签框架内约束文本。
任何方式我都可以包装文本并保持只有4行?
编辑:
尝试建议的代码
self.answer_text_label.text = self.answer.text;
[self.answer_text_label sizeToFit];
CGRect labelRect = self.answer_text_label.frame;
labelRect.origin.y = CGRectGetMaxY(labelRect);
labelRect.size = self.answer_text_label.frame.size;
self.answer_text_label.frame = labelRect;
结果如下。似乎没有解决我的问题
答案 0 :(得分:2)
尝试明确设置框架 -
[self.answer_text_label sizeToFit];
CGRect labelRect = self.answer_text_label.frame;
labelRect.origin.y = CGRectGetMaxY(labelRect);
labelRect.size = self.answer_text_label.frame.size;
self.answer_text_label.frame = labelRect;
编辑 - 不需要使用它,只需使用以下 - 删除这些代码只是在下面使用,没有框架的其他属性,也删除sizeToFit -
self.answer_text_label.numberOfLines = 4;
self.answer_text_label.lineBreakMode = UILineBreakModeWordWrap;
对于垂直对齐 - (使用上面的代码行,也可以使用它,并且不要使用大小来适应)
CGSize textSize = [self.answer_text_label.text sizeWithFont:self.answer_text_label.font
constrainedToSize:CGSizeMake(self.answer_text_label.frame.size.width, MAXFLOAT)
lineBreakMode:self.answer_text_label.lineBreakMode];
self.answer_text_label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);
答案 1 :(得分:0)
在iOS 6及更高版本中,使用NSLineBreakByWordWrapping
,而不是UILineBreakModeWordWrap。
self.answer_text_label.lineBreakMode = NSLineBreakByWordWrapping;