如何在Swift中将UITextField的topRight和bottomLeft角取整

问题描述

我想绕过UITextField topLeft和bottomright的拐角。

func conerRounderTextField(sides: CACornerMask) -> UITextField {
    let tf = UITextField()
    tf.backgroundColor = .white
    tf.clipsToBounds = true
    tf.layer.cornerRadius = 20
    tf.layer.maskedCorners = sides
    tf.layer.borderWidth = 1
    tf.layer.borderColor = UIColor.gray.cgColor
    return tf
}

并像这样调用TextField:

private let passwordTextField: UITextField = {
    let tf = Utillities().conerRounderTextField(sides: [.layerMaxXMinYCorner,.layerMinXMaxYCorner])
    return tf
}()

通过这种方式,我可以得到想要的设计,但TextField无法正常工作。

design

你能帮我吗?

解决方法

以下对我有用(Xcode 11.5):

class ViewController: UIViewController {

    func cornerRounderTextField(sides: CACornerMask) -> UITextField {
        let tf = UITextField()
        tf.backgroundColor = .white
        tf.clipsToBounds = true
        tf.layer.cornerRadius = 16
        tf.layer.maskedCorners = sides
        tf.layer.borderWidth = 1
        tf.layer.borderColor = UIColor.gray.cgColor
        return tf
    }
    
    private lazy var passwordTextField: UITextField = {
        let tf = cornerRounderTextField(sides: [.layerMaxXMinYCorner,.layerMinXMaxYCorner])
        tf.translatesAutoresizingMaskIntoConstraints = false
        return tf
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(passwordTextField)
        
        NSLayoutConstraint.activate([
            passwordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),passwordTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor),passwordTextField.widthAnchor.constraint(equalToConstant: 200),passwordTextField.heightAnchor.constraint(equalToConstant: 30)
        ])
    }
}

(您可以使用cmd + k切换键盘)