首页 > 解决方案 > 自定义 UITextField 中的边框宽度和占位符

问题描述

我想做这个 TextField

在此处输入图像描述

所以我写了这门课

class UnderLineTextField:UITextField{

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        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)

        textColor = UIColor.gold()
        backgroundColor = UIColor.clear

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

        attributedPlaceholder = NSAttributedString(string: "",
                                                  attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkgray()])}
}

但是有两个问题

  1. 下划线不等于TextField,如果我添加更多的宽度width: frame.size.width + 500,问题可以解决,但为什么呢?我应该传递给什么正确的值width:

  2. attributedPlaceholder将替换我在 xib 中设置的占位符,如何在不添加空字符串的情况下更改占位符?

在此处输入图像描述

在此处输入图像描述

标签: iosswiftuitextfield

解决方案


看来你的代码没问题。

使用以下代码设置占位符:

class UnderLineTextField:UITextField{

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor

        }
    }
    @IBInspectable var placeHolderText: String = "default place holder" {
        didSet {
            attributedPlaceholder = NSAttributedString(string: placeHolderText,
                                                       attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkGray])}

        }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        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)

        textColor = UIColor.lightGray
        backgroundColor = UIColor.clear

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

        attributedPlaceholder = NSAttributedString(string: placeHolderText,
                                                   attributes: [NSAttributedStringKey.foregroundColor: UIColor.darkGray])}
}

并在情节提要中设置占位符: 在此处输入图像描述

结果将如下所示:

在此处输入图像描述


推荐阅读