iOS UITextField 快速下划线样式

标签 ios swift uitextfield

UI Interface Login example

我添加了这张用户界面登录图片,希望您能看到。请注意,文本字段是透明的,但底部的线条除外。我要输入什么代码才能产生这种影响?我可以将必要的信息放在“用户定义的运行时属性”中吗?

最佳答案

Your output

如下所示创建 UITextField 的子类,并在 Storyboard中简单地将此类设置为 UITextField

通过@IBInspectable 支持 Swift 5

import UIKit

class HSUnderLineTextField: UITextField , UITextFieldDelegate {

    let border = CALayer()

    @IBInspectable open var lineColor : UIColor = UIColor.black {
        didSet{
            border.borderColor = lineColor.cgColor
        }
    }

    @IBInspectable open var selectedLineColor : UIColor = UIColor.black {
        didSet{
        }
    }


    @IBInspectable open var lineHeight : CGFloat = CGFloat(1.0) {
        didSet{
            border.frame = CGRect(x: 0, y: self.frame.size.height - lineHeight, width:  self.frame.size.width, height: self.frame.size.height)
        }
    }

    required init?(coder aDecoder: (NSCoder?)) {
        super.init(coder: aDecoder!)
        self.delegate=self;
        border.borderColor = lineColor.cgColor
        self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "",
                                                               attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])


        border.frame = CGRect(x: 0, y: self.frame.size.height - lineHeight, width:  self.frame.size.width, height: self.frame.size.height)
        border.borderWidth = lineHeight
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }

    override func draw(_ rect: CGRect) {
        border.frame = CGRect(x: 0, y: self.frame.size.height - lineHeight, width:  self.frame.size.width, height: self.frame.size.height)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        border.frame = CGRect(x: 0, y: self.frame.size.height - lineHeight, width:  self.frame.size.width, height: self.frame.size.height)
        self.delegate = self
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        border.borderColor = selectedLineColor.cgColor
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        border.borderColor = lineColor.cgColor
    }
}

enter image description here

从 Storyboard 中设置 lineColorselectedLineColor 并运行您的项目。

关于iOS UITextField 快速下划线样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38303520/

相关文章:

ios - UITextField 在编辑时剪切文本

ios - 如何将数据从导航栏上的右键传输到另一个 ViewController?

ios - 如何在我的 webview 加载结束之前显示启动图像?

ios - 如何创建一个里面有 2 个数组的字典?

ios - 类型 'NSArray' 的值没有成员 'indices'

swift - 当 Swift 结构是存储属性时,可以在堆上分配它吗?

swift - UI 测试删除文本字段中的文本

iphone - 修改plist不起作用

ios - NSURLResponse 返回内容范围,忽略我要求的范围

ios - 文本字段应该返回自动滚动屏幕