将layer.cornerRadius 50应用于按钮

时间:2016-03-09 17:32:25

标签: swift cocoa-touch uibutton storyboard

我的目标是创建一个带圆角的按钮(每侧半圈)。看起来应该是这样的:

enter image description here

在用户定义的运行时属性中,我将layer.cornerRadius设置为KeyPath,将50设置为Value(也尝试了49)。此外,我已经设置了"剪辑子视图"是的选项(如在这个答案:UIlabel layer.cornerRadius not working in iOS 7.1) 但是,编译结果在我的iPhone 5c(iOS 9.2.1)上看起来像这样:

enter image description here

(图片是在Photoshop中制作的,但确实是这样的)

角落是圆的,但显然有一个锚点缺失。关于如何获得理想结果的任何建议?

3 个答案:

答案 0 :(得分:1)

如果您想使用动态方法而不是使用固定值,请尝试此操作。

  let button = UIButton()
  button.layer.cornerRadius = button.frame.size.height/2-1

答案 1 :(得分:1)

cornerRadius值不会根据按钮高度自动更新,因此,从storyboard / xib指定时,您必须确保该值正好是按钮高度的一半。

通常,这是通过将按钮高度设置为常量(使用高度约束)并将cornerRadius设置为该常量的一半(例如,对于您想要100的高度cornerRadius来实现的。价值50)。

如果您需要自动更新解决方案,最简单的解决方案是继承UIButton并覆盖layoutSubviews

override func layoutSubviews() {
   super.layoutSubviews()

   self.layer.cornerRadius = self.frame.size.height / 2.0
}

然后在xib / storyboard中,您可以将按钮的类更改为自定义类。

答案 2 :(得分:0)

对我来说,下面的效果比其他任何东西都好 为圆角按钮创建一个类并创建 UIButton 的子类。

class RoundedButton: UIButton {

 //add your title color and background color outside the below override method
 
 override func draw(_ rect: CGRect) {
    layer.cornerRadius = frame.height / 2.0
    clipsToBounds = true
 }   
}