ios - 在子类中根据 UIButton 大小设置 cornerRadius 的最佳位置?

标签 ios iphone swift uibutton calayer

所以我将在应用程序中使用一些不同的圆形按钮(一直到圆形按钮),据我所知,实现此目的的最简单方法是设置按钮 CALayer 的 cornerRadius 属性。

但是,我不想为每个 Controller 中需要它的每个按钮手动执行此操作,所以我认为在 init 上设置它的简单子(monad)类就是这种方式。

我正在使用 Storyboard 和 Autolayout 来定位和调整按钮的大小,并将它们分配给这个子类。

class RoundedButton: UIButton {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = self.bounds.size.height / 2.0
        self.clipsToBounds = true
        NSLog("BUTTON BOUNDS: H-%f  W-%f", self.bounds.size.height, self.bounds.size.width)
        NSLog("BUTTON FRAME: H-%f  W-%f", self.frame.height, self.frame.width)
    }
}

但我发现在这一点上(即初始化),框架和边界的大小都不是最终的。对于 Storyboard 中尺寸(和约束)为 H40 x W40 的按钮,边界/框架尺寸显示为 H30 x W38。

这意味着 cornerRadius 没有得到我期望的值。

我已经确认在稍后的某个时间点(例如,当按钮已经可以响应点击时)它的框架/边界确实是 H40 x W40。

毕竟,我的问题是,在 UIButton 子类中,何时/何处可以使用实例的最终帧/边界值安全地设置 cornerRadius?

最佳答案

如果您希望在 View 通过 AutoLayout 之后执行您的代码,您必须在调用 super.layoutSubviews() 之后在 layoutSubviews 中执行此操作。

像这样:

class RoundedButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = bounds.size.height / 2.0
        clipsToBounds = true
    }
}

这段代码并不完美,因为当高度大于宽度时它不支持(虽然很容易修复......)。

关于ios - 在子类中根据 UIButton 大小设置 cornerRadius 的最佳位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653936/

相关文章:

ios - 编辑tableView时自定义单元格imageView移动到左侧

ios - 如何从 NSMutableArray 中删除 nil 对象?

ios - NSLog根本不显示

php - iOS推送通知返回码102

ios - GPUImage + Touch 模糊效果

ios - 找不到支持键盘 type 4 的键盘 iPhone-PortraitChoco-NumberPad

iphone - 如何以编程方式隐藏选项卡栏,然后展开 View 以适合

iphone - 迭代 UITableView 中的单元格的成本

ios - NavBar 在 iOS 13 Swift 中与状态栏重叠

swift - 将 TableViewController 设置为 Root View Controller