使用自动布局舍入视图?

时间:2017-11-13 09:39:38

标签: ios swift uiview autolayout

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

我以为我已经用以下代码解决了这个问题,但由于某些原因它没有在视图的第一次加载时执行,并且视图显示为方形,直到我按下屏幕视图并将其恢复(例如提升键盘和降低它)。我知道为什么或如何处理修复工作?

 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
        }

首次加载时在屏幕上按下视图之前:

view is still square-shaped

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

view is now rounded

1 个答案:

答案 0 :(得分:3)

您应该在viewDidLayoutSubviews中运行舍入代码,而>在布局具有正确的帧后运行

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

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
}