可应用于每个 UITextField 的自定义类 - Swift [英] Custom class that can be applied to every UITextField - Swift

查看:37
本文介绍了可应用于每个 UITextField 的自定义类 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程非常陌生,正在制作一个包含许多 UITextField 的项目.我想让文本字段在底部只有一个边框,以便看起来更干净,我在这里找到了一些应该可以实现这一点的代码.

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

如何创建一个类,以便我放置在故事板中的每个 UItext 字段都可以简单地使其成为所述类的一部分?我不想为每个 UITextField 复制和粘贴此代码.有没有办法做到这一点,我可以单独编辑应用此类的每个 UITextfield 的占位符文本?

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?

推荐答案

很简单,只要在任何类下输入此代码一次

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.

然后返回设计并在您拥有的所有 TextField 中选择它并运行

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

这篇关于可应用于每个 UITextField 的自定义类 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆