如果不直接在代码中设置按钮,我无法在 Xcode 5 中为按钮添加边框。如果不制作自定义背景图像,是否有可能无法在情节提要上执行此操作?
您可以使用关键路径。
例如图像上描述的角半径 (
layer.cornerRadius
)。
@IBInspectable
在情节提要中显示结果(如果您使用类别,请仅使用 cornerRadius
而不是 layer.cornerRadius
作为关键路径。
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
这是来自 Peter DeWeese 答案的类别,允许使用 keypath
layer.borderUIColor
设置边框颜色。
CALayer+XibConfiguration.h:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface CALayer(XibConfiguration)
// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;
@end
CALayer+XibConfiguration.m:
#import "CALayer+XibConfiguration.h"
@implementation CALayer(XibConfiguration)
-(void)setBorderUIColor:(UIColor*)color
{
self.borderColor = color.CGColor;
}
-(UIColor*)borderUIColor
{
return [UIColor colorWithCGColor:self.borderColor];
}
@end
斯威夫特3 如果你想在使用 IBInspectable 时在 IB 中看到结果,你必须扩展 UIView 并将属性添加到该类,即
@IBDesignable class MyView: UIView {}
extension MyView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor.init(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue.cgColor
}
}
}
简短回答:
layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor
长答案:
customUIView.layer.cornerRadius = 10
pcustomUIView.layer.borderWidth = 1
customUIView.layer.borderColor = UIColor.blue.cgColor
这对我有用 -
首次创建IBOutlet
@IBOutlet weak var btnOutlet: UIButton!
然后将其添加到viewDidLoad中
let btnHeight = btnOutlet.frame.size.height
let btnWidth = btnOutlet.frame.size.width
let frame = CGRect(x: btnHeight/2 , y: btnHeight - btnHeight/4 , width: btnWidth - btnHeight, height: 2)
let bottomBorder = UIView(frame: frame)
bottomBorder.backgroundColor = UIColor.gray
btnOutlet.addSubview(bottomBorder)
它适用于所有设备
您可以使用如下代码:
self.addButton.layer.borderColor = [[UIColor greenColor] CGColor];
请注意:
addButton
是IBOutlet。