swift3中UITextfield子类内的帧大小不正确

时间:2016-10-30 15:44:23

标签: ios swift swift3 xcode8

将Xcode版本升级到8,我发现很多问题,我仍然将我的swift2.3版本修复为swift3。我的一个问题是所有自定义UITextfield都不起作用,因为在我的项目中显示空白。以下是我的自定义UITextfield以及如何修复以在swift3中正确显示。

enter image description here

import UIKit

class OvalTextField: UITextField, UITextFieldDelegate {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        createBorder()
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let finalString = textField.text! + string;
        if (finalString != "") {
            textField.rightView?.isHidden = true
        }
        return true
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        createBorder()
    }

    func createBorder(){

        let errorImg = UIImageView (frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        errorImg.image = UIImage(named: "error")
        errorImg.contentMode = UIViewContentMode.left

        self.delegate = self
        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0).cgColor
        self.layer.cornerRadius = self.frame.size.height / 2
        self.layer.masksToBounds = true

        let gapLabel = UIView (frame: CGRect(x: 60, y: 0, width: 20, height: 40))
        self.leftView = gapLabel
        self.leftViewMode = UITextFieldViewMode.always

        /* Display that one when validation is failed */
        self.rightView = errorImg;
        self.rightViewMode = UITextFieldViewMode.always
    }
}

1 个答案:

答案 0 :(得分:3)

TextField正在从故事板中获取它的帧,因此在设置cornerRadius时你会得到不正确的帧大小。

设置转角半径时出错。

 self.layer.cornerRadius = self.frame.size.height / 2

将其替换为

self.layer.cornerRadius = 2

如果您覆盖drawRect方法并将cornerRadius设置为

,也可以更好
override func draw(_ rect: CGRect) {

     self.layer.cornerRadius = rect.size.height / 2

}