可以使UITextField这样吗?

时间:2019-07-10 18:12:09

标签: swift xcode uitextfield

情况:我想在xcode项目中为我的textField使用自定义UITextField类。 我想让textField看起来像这样:

My text field

我没有使边缘变圆并更改占位符颜色的问题,但是我不知道如何保持底部边缘平坦并仅在底部绘制黑色边框。

这是我的代码:

import UIKit

class GrayTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .grayf1f1f1
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
        layer.cornerRadius = 10
        clipsToBounds = true
    }

    override var placeholder: String? {
        didSet {
            let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .thin)]
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
        }
    }
}

我当前的结果:

Current result

2 个答案:

答案 0 :(得分:1)

在您的答案中,左下角和右下角仍然存在一些问题。

要获得准确的结果,请将您的UITextField Border Style更改为No Border

enter image description here

填充文字

class GrayTextField: UITextField {

    let padding = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 5)

    ..... Your Exact Code .....

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }
}

输出

enter image description here

答案 1 :(得分:0)

好吧,经过一番研究,我做到了。 这里是我的最终代码:

import UIKit

class GrayTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .grayf1f1f1
        clipsToBounds = true

        let maskPath = UIBezierPath(roundedRect: self.bounds,
                                    byRoundingCorners: [.topLeft, .topRight],
                                    cornerRadii: CGSize(width: 10.0, height: 10.0))

        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape

        addBottomBorder(with: .darkGray, andWidth: 1)
    }


    override var placeholder: String? {
        didSet {
            let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .thin)]
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
        }
    }

    func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
        border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
        addSubview(border)
    }
}

这是结果:

result

相关问题