ios - UIbutton 的圆角扰乱了其宽度

标签 ios swift uibutton

我想在三个按钮中进行舍入:

  • 第一个按钮的顶角
  • 第二个按钮的下角
  • 第三个按钮的所有四个角

我通过以下代码实现了这一点:

        button1.roundedButton1()
        button2.roundedButton2()
        button3.layer.cornerRadius = 5

extension UIButton {
    func roundedButton1(){
        let maskPAth1 = UIBezierPath(roundedRect: self.bounds,
                                     byRoundingCorners: [.topLeft , .topRight],
                                     cornerRadii:CGSize(width:5.0, height:5.0))
        let maskLayer1 = CAShapeLayer()
       // maskLayer1.frame = self.bounds
        maskLayer1.path = maskPAth1.cgPath
        self.layer.mask = maskLayer1
    }

    func roundedButton2(){
        let maskPAth1 = UIBezierPath(roundedRect: self.bounds,
                                     byRoundingCorners: [.bottomLeft , .bottomRight],
                                     cornerRadii:CGSize(width:5.0, height:5.0))
        let maskLayer1 = CAShapeLayer()
        maskLayer1.frame = self.bounds
        maskLayer1.path = maskPAth1.cgPath
        self.layer.mask = maskLayer1
    }
}

但是我的第一个和第二个按钮的宽度受到干扰。

enter image description here

如果我使用button2.layer.cornerRadius = 5,那么宽度就可以了。我已经搜索了它改变其宽度的代码,但没有找到任何合适的内容。这是我为 UIButton 找到的唯一可行的解​​决方案。谁能告诉我为什么按钮的宽度正在改变以及如何修复它?

按钮的约束如下:

enter image description here

最佳答案

您可以使用 UIViewUITapGestureRecognizer 来实现此结果,而不是使用 UIButton

添加此扩展

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

然后创建一个自定义 View 类

class CustomView: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()
        self.roundCorners([.topRight, .topLeft], radius: 5) // you can use .topRight , .topLeft , .bottomRight, .bottomLeft 
    }
}

然后在您的 View 中使用该类 refer this

希望这对您有帮助

关于ios - UIbutton 的圆角扰乱了其宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47508022/

相关文章:

iphone - 如何为 UILabel 复制?

ios - NSNotification:尝试在其 View 不在窗口层次结构中的 ViewController 上显示 UIAlertController

ios - 在swift iOS中计算高字节和低字节?

ios - UIButton 层样式使应用程序变慢

ios - 如何在按下按钮时从 UITextField 更新标签

iphone - UIButton 在动画期间不交互

ios - IF 比较 CGFloat 值 - Xcode 7 给出错误

ios - 如何定位 SCNCamera 以便在 View 中看到对象 "just fits"?

ios - Xamarin Forms (iOS) - 从选择器中删除快捷方式栏

arrays - 使 JSON 响应符合结构和数组 Swift