【问题标题】:How to change the cornerRadius of button from storyboard with custom IBDesignable class created如何使用创建的自定义 IBDesignable 类从情节提要中更改按钮的角半径
【发布时间】:2017-07-19 13:01:16
【问题描述】:

下面给出的类工作正常

@IBDesignable class iButton : UIButton {

@IBInspectable var cornerRadius : CGFloat = 0.0{
    didSet{
        layer.cornerRadius = cornerRadius
    }
}}

但问题是,当我在 Attribute Inspector 中为尺寸为(宽度:70,高度 70)的按钮设置cornerRadius 值 35 时。我在情节提要上得到了圆形按钮,但是在模拟器上运行它时,它不是圆形的,而是圆角矩形。

我在 xCode 上的设计视图是 iPhone-SE,并在 iPhone-7-plus 模拟器上模拟。

我还通过在 Size Inspector 上设置高度和宽度来启用自动调整大小。

据我所知,角半径应该是宽度的一半。当按钮通过自动调整大小调整大小时,为什么不调整角半径。我该如何解决这个问题?

提前致谢。

【问题讨论】:

  • 给出按钮约束,然后使用它来代替button.layer.cornerRadius = button.frame.width/2
  • 对于圆形按钮会有所帮助,但并非对所有情况都适用@DatForis

标签: ios xcode swift3 cornerradius ibinspectable


【解决方案1】:
import UIKit

@IBDesignable 
class RoundedCornerButton: UIButton {

    override func drawRect(rect: CGRect) {
        self.clipsToBounds = true
    }

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            self.layer.cornerRadius = cornerRadius
        }
    }
}

或者你可以查看这个链接这个链接了解更多信息

https://www.youtube.com/watch?v=JQ5i2YKwvJ8

【讨论】:

    【解决方案2】:

    谢谢你,我得到了答案。

    我们还需要缩放cornerRadius。

    layer.cornerRadius = cornerRadius * (UIScreen.main.bounds.width/320.0) //320.0 be my width of the screen that i designed on storyboard
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多