Answers:
您可以通过其基础CALayer属性设置标签的边框:
#import <QuartzCore/QuartzCore.h>
myLabel.layer.borderColor = [UIColor greenColor].CGColor
myLabel.layer.borderWidth = 3.0
斯威夫特5:
myLabel.layer.borderColor = UIColor.darkGray.cgColor
myLabel.layer.borderWidth = 3.0
#import <QuartzCore/QuartzCore.h>
myLabel.layer.borderColor = UIColor.greenColor().CGColor
您可以使用以下方法UILabel
及其边框。
这是这些标签的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
@IBOutlet weak var label6: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// label 1
label1.layer.borderWidth = 1.0
// label 2
label2.layer.borderWidth = 5.0
label2.layer.borderColor = UIColor.blue.cgColor
// label 3
label3.layer.borderWidth = 2.0
label3.layer.cornerRadius = 8
// label 4
label4.backgroundColor = UIColor.cyan
// label 5
label5.backgroundColor = UIColor.red
label5.layer.cornerRadius = 8
label5.layer.masksToBounds = true
// label 6
label6.layer.borderWidth = 2.0
label6.layer.cornerRadius = 8
label6.backgroundColor = UIColor.yellow
label6.layer.masksToBounds = true
}
}
请注意,在Swift中,无需导入QuartzCore
。
也可以看看
带有@IBDesignable的Swift 3/4
尽管几乎所有上述解决方案都可以正常工作,但我建议@IBDesignable
为此使用一个自定义类。
@IBDesignable
class CustomLabel: UILabel {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 2.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
您可以使用此存储库:GSBorderLabel
很简单:
GSBorderLabel *myLabel = [[GSBorderLabel alloc] initWithTextColor:aColor
andBorderColor:anotherColor
andBorderWidth:2];
Swift 4中的UILabel属性borderColor,borderWidth,cornerRadius
@IBOutlet weak var anyLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
anyLabel.layer.borderColor = UIColor.black.cgColor
anyLabel.layer.borderWidth = 2
anyLabel.layer.cornerRadius = 5
anyLabel.layer.masksToBounds = true
}