【问题标题】:Auto sizing UILabel with SnapKit使用 SnapKit 自动调整 UILabel 大小
【发布时间】:2017-04-14 21:17:02
【问题描述】:

假设CustomView's 大小为 300x300。 iconImageView 有它的大小和分配的约束。我不知道UILabel 中的文本要多长时间,所以我不想使UILabel 的大小保持不变。我的目标是将左侧约束固定到 iconImageView 的右侧,将右侧固定到 customView

override func updateConstraints() {
    super.updateConstraints()

    iconImageView.snp.updateConstraints { (make) in
        make.left.equalTo(customView).offset(10)
        make.centerY.equalTo(customView)
        make.size.equalTo(CGSize(width: 40.0, height: 40.0))
    }

    nameLabel.snp.updateConstraints { (make) in
        make.right.equalTo(customView).offset(-10)
        make.left.equalTo(iconImageView.snp.right).offset(10)
        make.centerY.equalTo(customView)
    }
}

当我尝试这种方法时出现错误:Unable to simultaneously satisfy constraints. 这样做的正确方法是什么?

【问题讨论】:

  • hmmm... 我刚刚尝试了您的代码,它运行良好。我假设这段代码在UIView 子类中?并且 那个 视图相对于它的 SuperView 有适当的约束?并且customView 有适当的约束使其成为 300x300 并定位在该视图内?
  • 这段代码在 UIView 子类中,并且相对于 superview 有适当的约束。当我滑动到另一个 ViewController 时出现错误,因为这个视图是 UIPageViewController 的一部分。
  • hmm... 猜想我们需要更多关于您何时收到错误的信息。不过,您应该首先阅读关于覆盖 updateConstraints() 的讨论(它可能只是为您提供开始所需的信息):developer.apple.com/reference/uikit/uiview/…

标签: swift uiview autolayout uilabel snapkit


【解决方案1】:

好吧,我想您的子视图对顶部/底部约束一无所知,这意味着视图不知道如何重新布局自己。试试这个:

override func updateConstraints() {
    super.updateConstraints()

    iconImageView.snp.updateConstraints { (make) in
        make.left.equalTo(customView).offset(10)
        make.centerY.equalTo(customView)

        // Also from my point of view this line \/ 
        // is not very readable
        //  make.size.equalTo(CGSize(width: 40.0, height: 40.0))
        // Changed to:
        make.width.height.equalTo(40.0)
    }

    nameLabel.snp.updateConstraints { (make) in
        make.right.equalTo(customView).offset(-10)
        make.left.equalTo(iconImageView.snp.right).offset(10)

        // Add:
        make.top.equalTo(customView.snp.top)
        make.bottom.equalTo(customView.snp.bottom)
    }
}

如果您想保持标签的“默认”高度(如果是空字符串等),您可以添加:

make.height.greaterThanOrEqual(40.0)

自动布局和框架也不能很好地相互配合,所以你应该在“updateConstraints”方法中布局你的自定义视图,类似于这样:

customView.snp.updateConstraints { (make) in 
     make.edges.equalTo(self)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2011-10-20
    • 2014-05-04
    • 2013-06-14
    • 2015-10-08
    • 2013-01-02
    相关资源
    最近更新 更多