[英]Button Border with Transparent Background in Swift
How can I make a UIButton
border to look alike in the below image (the "Getting Started") button with a transparent background? 如何在具有透明背景的下图(“入门”)按钮中使
UIButton
边框看起来相似?
How should I achieve this using storyboard or how to do it programmatically? 我应该如何使用情节提要或通过编程方式实现?
Setting the backgroundColor
to clearColor
makes the button transparent. 将
backgroundColor
设置为clearColor
可使按钮透明。
Try the code below for example. 例如,尝试下面的代码。 You can configure and vary the borderAlpha,cornerRadius and colours as your want.
您可以根据需要配置和更改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
using Extension: 使用扩展程序:
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
}
}
Usage: 用法:
let sampleUIButton = UIButton()
sampleUIButton.setUpLayer(sampleUIButton)
self.view.addSubview(sampleUIButton)
Using Swift 3, for Storyboard, just add this subclass to your project, then in the Identity Inspector, make this the class for the UIButton on your storyboard. 使用Swift 3,对于Storyboard,只需将此子类添加到您的项目中,然后在Identity Inspector中,将其设为Storyboard上UIButton的类。 You should then be able to adjust the boarder color and width.
然后,您应该能够调整寄宿生的颜色和宽度。
@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 迅捷5
Similar to @rakeshbs, but in 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.