Swift 带约束的圆形按钮

Swift rounded buttons with constraints

在 iOS 9 iPhone 应用程序中,我有一个按钮,我希望它有圆角,所以它是完全圆的。我在故事板中添加了一个按钮,并添加了两个约束以使其水平和垂直居中。这一切都有效,直到我添加了几行代码以将圆角应用于按钮。这是我的故事板:http://i.imgur.com/Nd3AnEl.png 然后我将以下代码行添加到我的视图控制器中:

startButton.backgroundColor = UIColor.clearColor()
startButton.layer.cornerRadius = 75
startButton.layer.borderWidth = 2
startButton.layer.borderColor = UIColor.whiteColor().CGColor

当我运行这是一个iPhone5s的模拟器时,边框乱了,像这样:http://i.imgur.com/m5akxO4.png 几天来我一直在尝试使按钮完全变圆,但没有结果。我能做什么?

cornerRadius 似乎比它的高度大。在您的视图控制器中尝试以下代码:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    startButton.backgroundColor = UIColor.clearColor()
    startButton.layer.cornerRadius = startButton.bounds.size.height / 2
    startButton.layer.borderWidth = 2
    startButton.layer.borderColor = UIColor.whiteColor().CGColor
}

首先将按钮做成完全正方形,然后将角圆化为其宽度或高度的一半。

例如:

// 200*200 square button
startButton.frame.size = CGSize(width: 200, height: 200)
startButton.backgroundColor = UIColor.clearColor()

// make the corner rounded like circle
startButton.layer.cornerRadius = startButton.frame.size.height/2

startButton.layer.borderWidth = 2
startButton.layer.borderColor = UIColor.whiteColor().CGColor

如何完全以编程方式创建它:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let button = UIButton(type: .Custom)
    button.frame = CGRectMake(160, 100, 50, 50) // (x, y, width, height)
    button.backgroundColor = UIColor.redColor()
    button.layer.cornerRadius = 0.5 * button.bounds.size.width
    button.layer.borderWidth = 2
    button.layer.borderColor = UIColor.whiteColor().CGColor
    button.setTitle("Hi!", forState: .Normal)

    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)


    view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
    print("hello!")
}

显然这些自定义中有很多是可选的(例如背景颜色),但只是为了向您展示您仍然可以使用按钮做任何您想做的事情。