【发布时间】:2015-02-13 04:52:46
【问题描述】:
如何使UIButton 边框看起来与下图(“入门”)按钮中的透明背景相似?
我应该如何使用情节提要或如何以编程方式做到这一点?
【问题讨论】:
-
你有什么尝试吗?你尝试了什么?什么不起作用?
如何使UIButton 边框看起来与下图(“入门”)按钮中的透明背景相似?
我应该如何使用情节提要或如何以编程方式做到这一点?
【问题讨论】:
将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
【讨论】:
斯威夫特 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)
【讨论】:
对于 Storyboard,使用 Swift 3,只需将此子类添加到您的项目中,然后在 Identity Inspector 中,将其设置为故事板上 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
}
}
【讨论】: