【问题标题】:How to make top edges of a UIbutton square in swift3 ios如何在swift ios中制作UIbutton正方形的顶部边缘
【发布时间】:2017-07-19 06:03:12
【问题描述】:
@IBOutlet weak var button: UIButton!
    override func viewDidLoad() {

        button.layer.borderWidth = 0.5
        button.layer.cornerRadius = 10
        button.layer.masksToBounds = true
        button.layoutMargins.left = 5
        //roundCorners(corners: [.bottomLeft, .bottomRight], radius: button.cornerRadius)
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

我有一个带有cornerRadius=10 的按钮。但我需要以方形显示按钮的顶部边缘。我怎样才能做到这一点?

【问题讨论】:

标签: ios swift uibutton


【解决方案1】:

您可以通过使用 UIBezierPath 实现此目的

let path = UIBezierPath(button.bounds,
                    byRoundingCorners:[.bottomRight, .bottomLeft],
                    cornerRadii: CGSize(width: 10, height:  10))

let maskLayer = CAShapeLayer()

maskLayer.path = path.cgPath
button.layer.mask = maskLayer

【讨论】:

  • 但是顶部边缘没有连接。它从边缘断开。
  • @Rakesh 没有得到你想要的?
  • 我需要将按钮的顶部边缘显示为方形,而底部边缘保持圆角
  • @Rakesh 上面的代码给出了底边和顶边的圆角半径保持不变
【解决方案2】:

您可以创建 UIView 的扩展,例如:

public extension UIView {

    /// Set some or all corners radiuses of view.
    ///
    /// - Parameters:
    ///   - corners: array of corners to change (example: [.bottomLeft, .topRight]).
    ///   - radius: radius for selected corners.
    public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: bounds,
                                byRoundingCorners: corners,
                                cornerRadii: CGSize(width: radius, height: radius))
        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape
    }

}

然后用它来圆你的按钮,比如:

yourBtn.round([.bottomLeft, .bottomRight], radius: 10)

【讨论】:

  • 我应该在哪里提供此代码? : yourBtn.round([.bottomLeft, .bottomRight], 半径: 10)
  • @Rakesh 你可以在 viewDidLoad() 方法中添加这个
【解决方案3】:

在 swift 3.0 中,您可以在视图控制器的 viewDidload 方法中尝试此代码

let rectShape = CAShapeLayer()
rectShape.bounds = self.yourBtnName.frame
rectShape.position = self.yourBtnName.center
rectShape.path = UIBezierPath(roundedRect: self.yourBtnName.bounds, byRoundingCorners: [.bottomLeft , .bottomRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath

//Here I'm masking the textView's layer with rectShape layer
self.yourBtnName.layer.mask = rectShape

你的按钮看起来像

【讨论】:

    【解决方案4】:
    button.layer.cornerRadius = 2;
    button.layer.borderWidth = 1;
    button.layer.borderColor = UIColor.whiteColor().CGColor
    

    还可以设置按钮的高度和宽度(10,10)

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 2019-03-25
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      相关资源
      最近更新 更多