如何在 Swift 中使按钮具有圆角边框?


在 Swift 中,您可以使用 UIButton 的 layer 属性来设置其边框的圆角半径。您可以使用 layer (CALayer) 属性来应用边框宽度和颜色到按钮。此外,相同的属性提供了访问 cornerRadius 属性以使按钮变圆的功能。

我们将使用以下步骤使按钮具有圆角和边框

步骤 1 − 在此步骤中,创建具有基本自定义的按钮对象。

步骤 2 − 在此步骤中,向按钮添加边框和圆角半径。

步骤 3 − 在此步骤中,使按钮变圆。

示例

在此步骤中,您将创建一个按钮并进行一些基本自定义。以下是代码。

import UIKit
class TestController: UIViewController {   
   private let loginButton = UIButton()    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }    
   private func initialSetup() {        
      // basic setup
      view.backgroundColor = .white
      navigationItem.title = "UIButton"
        
      // log in button customization
      loginButton.setTitle("Button with rounded border", for: .normal)
      loginButton.setTitleColor(.red, for: .normal)
        
      // adding the constraints to the login button
      view.addSubview(loginButton)
      loginButton.translatesAutoresizingMaskIntoConstraints = false
      loginButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      loginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
      loginButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
      loginButton.widthAnchor.constraint(equalToConstant: 280).isActive = true
   }
}

输出

添加边框和圆角半径

在此步骤中,我们将向按钮应用圆角半径和边框宽度。以下是一个示例 -

示例

private func initialSetup() {   
   // basic setup
    
   // log in button customization
    
   // adding the constraints to the login button
    
   addButtonBorder()
}
private func addButtonBorder() {
   loginButton.layer.borderColor = UIColor.red.cgColor
   loginButton.layer.borderWidth = 1.5
   loginButton.layer.cornerRadius = 10.0
   loginButton.layer.masksToBounds = true
}

输出

使按钮具有圆角和边框

在此步骤中,我们将使按钮具有圆角和边框。以下是一个示例 -

示例

private func initialSetup() {
   // basic setup
   // log in button customization
   // adding the constraints to the login button
   makeButtonRounded()
}
private func makeButtonRounded() {
   loginButton.layer.borderColor = UIColor.red.cgColor
   loginButton.layer.borderWidth = 1.5
   loginButton.layer.cornerRadius = 25.0 // height / 2
   loginButton.layer.masksToBounds = true
}

输出

结论

总之,要在 Swift 中使按钮具有圆角边框,您可以使用 UIButton 的 layer 属性来设置圆角半径、边框宽度和边框颜色。

更新于: 2023年2月28日

6K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.