通过 viewDidAppear() 或 viewWillLayoutSubviews() 设置圆角半径?

Setting corner radius through viewDidAppear() or viewWillLayoutSubviews()?

总而言之,通过在 viewWillLayoutSubviews() 中获取按钮边界并将高度除以二,在我的应用程序中为我的 UIButton 设置圆角半径以获得左右边缘。但是,如果我通过 UIBarButtonItem() 导航到另一个屏幕,旋转设备,然后使用 UIButtons() 导航回屏幕,它们不是圆形的。角半径仍然基于先前方向的按钮尺寸。我尝试使用 viewDidAppear,但在设置角半径时存在 second/noticable 延迟。

有没有办法加快viewDidAppear的进程?我不认为 viewWillAppear 会起作用,因为视图控制器不知道我正在更改的 uibutton(s) 的默认(方形)尺寸。

我正在开发的应用程序是这样的:

Screenshots of my current application from loading screen to the point of the corner radius not being updated correctly

请改用 viewDidLayoutSubviews,因为此时您将拥有更新的边界,但在 viewWillLayoutSubviews 中还没有。

或者我可能建议有一个按钮 subclass 在它自己的 layoutSubviews 中进行舍入,使您的视图控制器不必遍历按钮并舍入它们。

例如:

@IBDesignable
class RoundedButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        let radius = min(bounds.width, bounds.height) / 2
        layer.cornerRadius = radius
    }

}

然后只需使用 class 而不是 UIButton。结果: