我有一个UITextField,我希望它具有高度和圆角以及自定义边框颜色。我尝试过:
为TextField创建一个@IBOutlet:
@IBOutlet weak var messageInputField: UITextField!
在viewWillAppear中,我有:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
messageInputField.layer.borderColor = UIColor(red:0.95, green:0.71, blue:0.01, alpha:1).cgColor
messageInputField.borderStyle = UITextBorderStyle.roundedRect
}
输出为:
圆角有效,但是我在代码中指定的颜色在哪里?如何设置边框的颜色?
答案 0 :(得分:1)
您必须添加messageInputField.layer.borderWidth = 1.0
或任何您想要的borderWidth
...
请注意,如果要使用自定义边框,则不能使用roundedRect
。对于自定义的圆形边框,请执行以下操作:
borderStyle
属性设置为none
borderColor
和borderWidth
添加自定义边框cornerRadius
设置为所需的值intrinsicContentSize
(或添加高度限制)以确定默认高度textRect
和editingRect
以添加正确的插图示例:
@IBDesignable
class CustomRoundedTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
borderStyle = .none
layer.borderColor = UIColor.orange.cgColor
layer.borderWidth = 2
layer.cornerRadius = 8
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: 30)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return super.textRect(forBounds: bounds).insetBy(dx: 8, dy: 0)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return super.editingRect(forBounds: bounds).insetBy(dx: 8, dy: 0)
}
}