Swift中透明背景的按钮边框

17

如何使一个 UIButton 边框看起来像下面图片中的"Getting Started"按钮并具有透明背景?

我应该如何在storyboard上实现这个效果,或者如何通过编程实现它?

enter image description here


3
你有尝试过什么吗?你尝试了什么?什么没有起作用? - Aaron Brager
4个回答

35

backgroundColor设置为clearColor可以使按钮透明。
尝试下面的代码示例。您可以根据需要配置和变化borderAlphacornerRadius和颜色。

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

4

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

3
使用扩展:
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)

1

使用Swift 3,对于Storyboard,只需将此子类添加到您的项目中,然后在Identity Inspector中,将其设置为Storyboard上UIButton的类。然后,您应该能够调整边框颜色和宽度。

@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
 }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接