swift - 在 Swift 的 UITableViewCell 中以编程方式布局 UILabel 和 UIView subview 的最佳方法

标签 swift ios-autolayout uitableview

使用 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/

相关文章:

ios - NSPredicate 没有正确过滤 TableView

ios - UIcollectionViewCell 中 UITableView 的动态高度

ios - UITableView 和 presentViewController 需要点击 2 次才能显示

第一行和第二行之间缺少 swift tableview 分隔线

ios - 如何在后端作业中实现旋转轮?

ios - 从 AppDelegate 执行 segue

ios - UIScrollView 如何约束充当所有其他 View 容器的 subview ?

ios - iOS:自动布局多个按钮

objective-c - iOS 8 CGAffineTransformMakeScale + 自动布局不再工作

ios - UITableView 在单元格刷新时滚动到顶部