如何自定义UITextField?

时间:2016-10-09 02:58:54

标签: ios swift

我正在关注这个answer来创建一个自定义的UITextField,但是,我无法得到相同的结果,这就是我如何做到的:

方法1 (与原始答案完全相同):

extension UITextField {

    func useUnderLine() {
        let border = CALayer()
        let borderWidth = CGFloat(1.0)
        border.borderColor = UIColor.white.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
        border.borderWidth = borderWidth
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    firstTextField.useUnderLine()
}

方法2 (使用自定义类):

class CustomTextField: UITextField {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    let borderWidth = CGFloat(1.0)
    self.layer.borderColor = UIColor.white.cgColor
    self.layer.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
    self.layer.borderWidth = borderWidth
    self.backgroundColor = UIColor.black
    self.layer.masksToBounds = true
}
}

这两种方法都不起作用,但是,我得到了不同的结果:

第一个文本字段使用方法1,另外3个使用方法2

  

我想要一个只有底线的文本字段,我该怎么做?

修改(这是设置出口的方式):

@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: CustomTextField! { didSet { secondTextField.delegate = self } }
@IBOutlet weak var thirdTextField: CustomTextField! { didSet { thirdTextField.delegate = self } }
@IBOutlet weak var fourthTextField: CustomTextField! { didSet { fourthTextField.delegate = self } }

1 个答案:

答案 0 :(得分:5)

如果您使用故事板创建textField,请使用以下内容:

firstTextField.borderStyle = .none
firstTextField.layoutIfNeeded()

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor

print(firstTextField.frame)
border.frame = CGRect(x: 0, y: firstTextField.frame.size.height - width, width:  firstTextField.frame.size.width, height: firstTextField.frame.size.height)
border.borderWidth = width

firstTextField.layer.addSublayer(border)
firstTextField.layer.masksToBounds = true

如果您以编程方式创建textField ,请使用以下内容:

let textField = UITextField(frame: CGRect(x: 0, y: 20, width: 100, height: 20))

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

border.borderWidth = width
textField.borderStyle = .none
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true

self.view.addSubview(textField)

会给你:
enter image description here