【问题标题】:Rounding views with Auto Layout?使用自动布局舍入视图?
【发布时间】:2017-11-13 09:39:38
【问题描述】:

我想在使用自动布局时创建圆形视图,因此,我无法在视图中设置特定的半径值。

我以为我已经用下面的代码解决了这个问题,但是由于某种原因它在视图的第一次加载时没有执行,并且视图看起来是方形的,直到我推动屏幕的视图并将它带回来(例如提高键盘并降低它)。知道为什么或如何解决问题吗?

 override func viewWillLayoutSubviews() {
    self.myProfileView.userImage.layer.cornerRadius = self.myProfileView.userImage.frame.size.width * 0.5
    self.myProfileView.userImage.layer.borderWidth = 2
    self.myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}

约束:

userImage.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).multipliedBy(0.25)
            userImage.heightAnchor.constraint(equalTo: userImage.widthAnchor).isActive = true
            userImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.40).isActive = true
        }

在首次加载时将视图推送到屏幕之前:

在我打开和关闭键盘后,将视图关闭并返回屏幕:

【问题讨论】:

    标签: ios swift uiview autolayout


    【解决方案1】:

    您应该改为在 viewDidLayoutSubviews 中运行舍入代码,该代码布局具有正确的框架之后运行。

    另外,在访问其大小之前,为myProfileView 执行layoutIfNeeded()

    override func viewDidLayoutSubviews() {
        myProfileView.layoutIfNeeded()
    
        myProfileView.userImage.layer.cornerRadius = myProfileView.userImage.frame.size.width * 0.5
        myProfileView.userImage.layer.borderWidth = 2
        myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
    }
    

    【讨论】:

    • 我看到了你的逻辑,但不幸的是这也没有效果,问题仍然存在
    • 尝试在这段代码之前运行myProfileView.layoutIfNeeded()
    • 谢谢解决它,如果你能更新你的答案我投票成功
    • 出于兴趣,我如何在 tableview 单元格内的视图上调用它?
    • 您应该覆盖单元格的layoutSubviews 函数。 (别忘了一开始就打电话给super.layoutSubviews()。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多