使用 Swift 和自动布局,在单元格中放置标签和自定义 View 的最佳方式是什么?我想要左边的标签和右边的 View 。 View 可以是 UIView 的任何子类。我遇到的一个问题是调整标签的宽度以适合文本。我希望自定义 View 占用剩余空间。我不喜欢使用视觉格式,而是使用 NSLayoutConstraint():
func tableView(aTableView: UITableView, cellForRowAtIndexPath anIndexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(frame: CGRect(x: 0.0, y: 0.0, width: aTableView.bounds.size.width, height: aTableView.estimatedRowHeight))
let titleLabel = UILabel()
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.text = "some text"
titleLabel.sizeToFit()
cell.contentView.addSubview(titleLabel)
titleLabel.layer.borderColor = UIColor.redColor().CGColor
titleLabel.layer.borderWidth = 1.0
cell.contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: cell.contentView, attribute: .Left, multiplier: 1.0, constant: 0.0))
let customView = UIView()
cell.contentView.addSubview(customView)
cell.contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .Left, relatedBy: .Equal, toItem: titleLabel, attribute: .Right, multiplier: 1.0, constant: 0.0))
cell.contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .Right, relatedBy: .Equal, toItem: cell.contentView, attribute: .Right, multiplier: 1.0, constant: 0.0))
return cell
}
最佳答案
尝试添加以下行:
customView.translatesAutoresizingMaskIntoContraints = false
您可能还需要一个额外的约束来定义 UILabel 的最大尺寸或 UIView 的最小尺寸。
因为您有 numberOfLines = 0
,UILabel 不知道何时换行,因为没有指定约束。
希望对你有帮助
关于swift - 在 Swift 的 UITableViewCell 中以编程方式布局 UILabel 和 UIView subview 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805766/