我当前正在构建一个可重用的视图,该视图利用了UITableView随其单元格提供的动态调整大小。

我要实现的目标是根据单元格中定义的size属性中指定的大小为单元格中的视图提供宽度和高度,在设置后,我使用configure函数将其传递给了视图视图的大小。

然后,我将其以xAxis为中心,并使用结构内的一个属性(仅是UIEdgeInset属性)在视图周围应用任何边距。使用SnapKit库,如下所示。

    if  let formImageItem = formImageItem,
        let size = formImageItem.size {

        formItemImgVw = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        formItemImgVw?.image = formImageItem.image
        formItemImgVw?.contentMode = formImageItem.aspectFit

        contentView.addSubview(formItemImgVw!)

        formItemImgVw?.snp.makeConstraints({ (make) in
              make.size.equalTo(CGSize(width: size.width, height: size.height))
              make.top.equalTo(formImageItem.margin.top)
              make.bottom.equalTo(formImageItem.margin.bottom)
              make.centerX.equalToSuperview()
        })
    }

我似乎遇到的问题是我收到以下警告。
2018-10-12 14:57:34.101532+0100 xxxx Dev[6104:2160548] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<SnapKit.LayoutConstraint:[email protected]#61 UIImageView:0x10530a940.height == 114.0>",
    "<SnapKit.LayoutConstraint:[email protected]#62 UIImageView:0x10530a940.top == UITableViewCellContentView:0x105503500.top>",
    "<SnapKit.LayoutConstraint:[email protected]#63 UIImageView:0x10530a940.bottom == UITableViewCellContentView:0x105503500.bottom>",
    "<NSLayoutConstraint:0x2837e2580 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x105503500.height == 44   (active)>"
)

Will attempt to recover by breaking constraint
<SnapKit.LayoutConstraint:[email protected]#61 UIImageView:0x10530a940.height == 114.0>

我了解这基本上告诉我,它正在选择使用默认设置为表格视图单元格的高度44。但是我似乎无法理解为什么它使用此默认高度,而不是我在约束内定义的高度并将其应用于视图,同时还增加了顶部和底部的间距。

同样,在使用调试器检查UI时,似乎根本没有设置高度,并且您可以看到44的高度只是剪切整个imageview。

ios - SnapKit和动态UITableViewCell的布局不正确-LMLPHP

因此,最终我要实现的功能是为视图提供定义的高度和宽度,并使用值应用顶部和底部间距(边距)以调整当前所在单元格的大小。

最佳答案

您需要降低底部约束的优先级,因此请替换为

make.bottom.equalTo(formImageItem.margin.bottom)


make.bottom.equalTo(formImageItem.margin.bottom).priority(999)

加上viewDidLoad
tableView.estimatedRowHeight = 120
tableView.rowHeight = UITableViewAutomaticDimension

Abd不实现heightForRowAt

关于ios - SnapKit和动态UITableViewCell的布局不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52781359/

10-10 20:46