【问题标题】:Swift rounded buttons with constraints [closed]带有约束的 Swift 圆形按钮 [关闭]
【发布时间】:2015-09-18 14:52:22
【问题描述】:

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

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

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

【问题讨论】:

  • 你可以尝试这样的事情:yourButton.frame = CGRectMake(100, 100, 75, 75) yourButton.layer.cornerRadius = yourButton.bounds.size.width / 2.0 yourButton.layer.masksToBounds = true
  • 我删除了cornerRadius并将masksToBounds设置为true,现在我在按钮周围有一个方形边框。现在我明白了为什么我会得到第二个屏幕截图上的效果。按钮大小为 150x150,但边框显示在文本周围,而不是 150x150 周围。我该怎么做才能使边框出现在 150x150 周围?
  • 根据提问者的要求关闭。

标签: ios iphone swift ios9


【解决方案1】:

完全以编程方式创建它怎么样:

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!")
}

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

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      【解决方案3】:

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

      例如:

      // 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 2014-12-16
        • 2015-10-07
        • 1970-01-01
        • 1970-01-01
        • 2020-03-24
        相关资源
        最近更新 更多