ppshein ppshein - 1 month ago 18
Swift Question

Incorrect frame size inside UITextfield Subclass in swift3

Upgrading Xcode version to 8, I've found tons of problem that I'm still fixing almost my swift2.3 version to swift3. One of my problem is all custom UITextfield does not work at all as displaying blank in my project. Following is my custom UITextfield and how to fix to be displayed correctly in 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
}
}

Answer

TextField is getting it's frame from the storyboard so you are getting incorrect frame size while setting cornerRadius.

You have error while setting the corner radius.

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

Replace this with

self.layer.cornerRadius = 2

Or also better if you override drawRect method and set cornerRadius as

override func draw(_ rect: CGRect) {

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

}
Comments