我有一个自定义tableViewCell
。 questionContent
是一个标签,我设置:
numberOfLines = 0
lineBreakMode = NSLineBreakMode.ByWordWrapping
但它没有包装。
这是questionContent
label:
let questionContent: UILabel = {
let tempView = UILabel()
tempView.numberOfLines = 0
tempView.font = UIFont.systemFontOfSize(15)
tempView.lineBreakMode = NSLineBreakMode.ByWordWrapping
tempView.backgroundColor = UIColor.redColor()
return tempView
}()
在layoutSubviews()
我设置它的框架
//questionContent
let questionContentX = avatorImageX
let questionContentY = CGRectGetMaxY(avatorImage.frame) + answeModel!.marginTopBottomLeftOrRight
let questionContentWidth = kScreenWidth - answeModel!.marginTopBottomLeftOrRight * 2
let questionContentHeight = answeModel!.contentRealSize.height
questionContent.frame = CGRectMake(questionContentX, questionContentY, questionContentWidth, questionContentHeight)
第一个数据questionContent.text = "Ssddfghjj ssddfghjjkk sssssffhjjk sasdfgghjjjkkllljhhgggggffdddssssaaaasfghjkkllnnvcczzzeefggghjjkkkklllkjhggtrrrddssdfcvvvxxcbbb"
questionContent.frame
是(8.0, 46.0, 304.0, 84.0)
但它没有包裹。这是截图
试试这段代码:
添加sizeToFit
线并尝试。
let questionContent: UILabel = {
let tempView = UILabel()
tempView.numberOfLines = 0
tempView.font = UIFont.systemFontOfSize(15)
tempView.lineBreakMode = NSLineBreakMode.ByWordWrapping
tempView.sizeToFit()
tempView.backgroundColor = UIColor.redColor()
return tempView
}()
这对我有用。
let questionContent: UILabel = {
let tempView = UILabel()
tempView.numberOfLines = 0
tempView.font = UIFont.systemFontOfSize(15)
tempView.lineBreakMode = NSLineBreakMode.ByWordWrapping
tempView.backgroundColor = UIColor.redColor()
tempView.text = " This is two long text.This is two long text.This is two long text.This is two long text.This is two long text.This is two long text.This is two long text.";
tempView.frame = CGRectMake(0, 0, 200, 10.0);
tempView.sizeToFit()
return tempView
}()
无需写入layoutsubview()方法。
我只是陷入同样的问题。我正在将标签添加到单元格中,如下所示:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(messageText) // add to cell itself
}
经过很长一段时间后,改为:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(messageText)
}
只需要将标签添加到contentView