Swift 中具有透明背景的按钮边框

Button Border with Transparent Background in Swift

如何使 UIButton 边框看起来与下图中的透明背景按钮("Getting Started")相似?

我应该如何使用情节提要或如何以编程方式实现此目的?

backgroundColor 设置为 clearColor 使按钮透明。
例如尝试下面的代码。您可以根据需要配置和改变 borderAlpha、cornerRadius 和颜色。

let borderAlpha : CGFloat = 0.7
let cornerRadius : CGFloat = 5.0

button.frame = CGRectMake(100, 100, 200, 40)
button.setTitle("Get Started", forState: UIControlState.Normal)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.clearColor()
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
button.layer.cornerRadius = cornerRadius

使用扩展:

extension UIButton
{
 func setUpLayer(sampleButton: UIButton?) {
  sampleButton!.setTitle("GET STARTED", forState: UIControlState.Normal)
  sampleButton?.tintColor =  UIColor.whiteColor()
  sampleButton!.frame = CGRect(x:50, y:500, width:170, height:40)
  sampleButton!.layer.borderWidth = 1.0
  sampleButton!.layer.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
  sampleButton!.layer.cornerRadius = 5.0

  sampleButton!.layer.shadowRadius =  3.0
  sampleButton!.layer.shadowColor =  UIColor.whiteColor().CGColor
  sampleButton!.layer.shadowOpacity =  0.3
 }

}

用法:

  let sampleUIButton =  UIButton()
  sampleUIButton.setUpLayer(sampleUIButton)
  self.view.addSubview(sampleUIButton)

Using Swift 3,对于 Storyboard,只需将此子class 添加到您的项目中,然后在 Identity Inspector 中,将其设为故事板上 UIButton 的 class。然后您应该能够调整边界颜色和宽度。

@IBDesignable class CustomButton: UIButton {

 @IBInspectable var borderColor: UIColor = UIColor.white {
    didSet {
        layer.borderColor = borderColor.cgColor
    }
 }

 @IBInspectable var borderWidth: CGFloat = 2.0 {
    didSet {
        layer.borderWidth = borderWidth
    }
 }

 override public func layoutSubviews() {
    super.layoutSubviews()
    clipsToBounds = true
 }
}

Swift 5

类似于@rakeshbs,但在Swift 5:

    let borderAlpha : CGFloat = 0.7
    let cornerRadius : CGFloat = 5.0

    self.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
    self.setTitle("Login", for: UIControl.State.normal)
    self.setTitleColor(UIColor.white, for: UIControl.State.normal)
    self.backgroundColor = UIColor.clear
    self.layer.borderWidth = 1.0
    self.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).cgColor
    self.layer.cornerRadius = cornerRadius