我正在尝试使用约束创建带图像和标签的自动调整大小的UITableViewCell。当我为图像定义高度时,某些单元格的标签高度设置不正确,为什么会这样?
下图显示了标签高度不正确且高度正确的单元格。
带有约束的自定义单元格的代码是:
import UIKit
class NewsItemCell : UITableViewCell {
var msg: UILabel
var img: UIImageView!
required init(coder aDecoder: NSCoder) {
msg = UILabel()
msg.numberOfLines = 0
msg.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
msg.lineBreakMode = .ByWordWrapping
img = UIImageView()
img.contentMode = .ScaleAspectFill
img.clipsToBounds = true
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
addSubview(msg)
addSubview(img)
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
msg.setTranslatesAutoresizingMaskIntoConstraints(false)
img.setTranslatesAutoresizingMaskIntoConstraints(false)
let c0 = NSLayoutConstraint(item: img, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0);
let c1 = NSLayoutConstraint(item: img, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0)
let c2 = NSLayoutConstraint(item: img, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0)
let c3 = NSLayoutConstraint(item: msg, attribute: .Top, relatedBy: .Equal, toItem: img, attribute: .Bottom, multiplier: 1, constant: 5)
let c4 = NSLayoutConstraint(item: msg, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: -5)
let c5 = NSLayoutConstraint(item: img, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 120)
let c6 = NSLayoutConstraint(item: msg, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant:-5)
let c7 = NSLayoutConstraint(item: msg, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant:5)
addConstraint(c0)
addConstraint(c1)
addConstraint(c2)
addConstraint(c3)
addConstraint(c4)
addConstraint(c5)
addConstraint(c6)
addConstraint(c7)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
答案 0 :(得分:0)
啊!那么你看,问一半解决方案^。^
事实证明我正在更新错误的委托功能中的msg.text
值。我在msg.text
设置了willDisplayCell
,但我必须在cellForRowAtIndexPath
中设置它。