如何修复这些约束,使文本出现在 UITableViewCell 中图像的右侧?

Posted

技术标签:

【中文标题】如何修复这些约束,使文本出现在 UITableViewCell 中图像的右侧?【英文标题】:How can I fix these constraints so the text appears to the right of the image in my UITableViewCell? 【发布时间】:2020-03-26 01:19:15 【问题描述】:

我的 UITableViewCells 约束存在问题,我似乎无法弄清楚如何修复我编写的这些约束。我希望文本跨越单元格并从最左侧图像的右侧开始。如果可能的话,我只希望文本在单元格中居中,但我不确定如何实现这个目标。截至目前,我已将宽度设置为文本的高度,但如果您能够帮助指导我使文本与左侧的图像相邻,那将不胜感激。我还在下面附上了当前设置的图片(您会同意它看起来很丑)

代码如下:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) 
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    self.addSubview(mainImageView)
    self.addSubview(messageView)

    mainImageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
    mainImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    mainImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    mainImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
    mainImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true

    messageView.leftAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    messageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    messageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    messageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    messageView.widthAnchor.constraint(equalTo: self.heightAnchor).isActive = true

enter image description here

【问题讨论】:

【参考方案1】:

首先你需要设置

translatesAutoresizingMaskIntoConstraints = false

为每个组件添加约束之前。

在此之后,您还可以设置 imageview 的顶部、底部和高度、宽度约束。每个约束都会与其他约束发生冲突。您必须只使用其中一组。顶部、底部或高度、宽度。

不推荐使用顶部、底部约束。它有时会使图像有弹性。最好使用宽度高度约束并将图像居中到 Y 中心。

    mainImageView.translatesAutoresizingMaskIntoConstraints = false
    mainImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor,constant:16).isActive = true
    mainImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
    mainImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
    mainImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    messageView.translatesAutoresizingMaskIntoConstraints = false
    messageView.leadingAnchor.constraint(equalTo: mainImageView.trailingAnchor, constant: 16).isActive = true
    messageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
    messageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

您可以使用 textAlignment 在消息视图中将文本居中

【讨论】:

非常感谢您解决了这个问题,非常感谢您的帮助

以上是关于如何修复这些约束,使文本出现在 UITableViewCell 中图像的右侧?的主要内容,如果未能解决你的问题,请参考以下文章

当 UITableView 加载并在滚动后得到修复时,UILabel 向左移动

使用动态约束对齐文本字段

如何使视图修复屏幕IOS 8?

iOS:为啥我的子视图在滚动视图中出现大间距

如何在 iOS 中对齐文本视图和标签中的文本

如何允许自动调整UIButton的大小以满足间距约束