Custom class that can be applied to every UITextField - Swift

↘锁芯ラ 提交于 2019-12-07 18:26:31

问题


Im very new to programming and am making a project that will have many UITextFields. I want to have the text fields only have a border on the bottom for a cleaner look, and I found some code here that is supposed to make that happen.

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.layer.addSublayer(border)
textField.layer.masksToBounds = true

How can I make a class so that every UItext field I place in the storyboard I can simply make it part of said class? I don't want to copy and paste this code for each UITextField. And is there a way to do it where I could individually edit the placeholder text for each UITextfield this class is applied to?


回答1:


it's very easy just enter this code in under any class only one time

    @IBDesignable
    open class customUITextField: UITextField {

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)  
        setup()
    }
}

In "Setup" function put all customizations you want.

After that back to design and choose it in all TextField you have and Run




回答2:


Here is an example:

class CustomTextField: UITextField {

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

        border.borderWidth = width
        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}

To simplify your border code you could do this:

layer.borderWidth = 2.0
layer.masksToBounds = true


来源:https://stackoverflow.com/questions/51681626/custom-class-that-can-be-applied-to-every-uitextfield-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!