【发布时间】:2017-08-20 01:10:50
【问题描述】:
如何在 Swift 3 中更改所有 TextField 边框颜色 我构建了一个 iPad 应用程序。 我的 .xib 文件中有很多 TextField,现在我想更改边框颜色,但是写特定文本字段的行太多了,所以有什么方法可以解决这个问题?
【问题讨论】:
-
您可以扩展文本字段。
标签: ios swift uitextfield border-color
如何在 Swift 3 中更改所有 TextField 边框颜色 我构建了一个 iPad 应用程序。 我的 .xib 文件中有很多 TextField,现在我想更改边框颜色,但是写特定文本字段的行太多了,所以有什么方法可以解决这个问题?
【问题讨论】:
标签: ios swift uitextfield border-color
添加此扩展程序可为项目中的所有文本字段创建边框。
extension UITextField
{
open override func draw(_ rect: CGRect) {
self.layer.cornerRadius = 3.0
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.masksToBounds = true
}
}
【讨论】:
self.layer.borderColor = UIColor.uicolorFromHex(999999, alpha: 1)).cgColor
extension UITextField {
func cornerRadius(value: CGFloat) {
self.layer.cornerRadius = value
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.masksToBounds = true
}}
【讨论】:
您应该创建一个新类,它是 UITextField 的子类,如下所示:
import UIKit
class YourTextField: UITextField {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setBorderColor()
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.setBorderColor()
}
func setBorderColor(){
self.layer.borderColor = .red // color you want
self.layer.borderWidth = 3
// code which is common for all text fields
}
}
现在打开 xib 选择所有文本字段。
在身份检查器中,将自定义类更改为 YourTextField
这样,即使您的项目中有 1000 个文本字段,也无需为此多写一行。
【讨论】: