如何使一个 UIButton
边框看起来像下面图片中的"Getting Started"按钮并具有透明背景?
我应该如何在storyboard上实现这个效果,或者如何通过编程实现它?
将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
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
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)
使用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
}
}