vimal prakash vimal prakash - 6 months ago 44
Swift Question

App freezes while creating custom textfield in ios swift

I am try to develop a custom textbox in swift iOS, it's freezing after typing 2 letters

class TextField: UITextField , UITextFieldDelegate {
let inset: CGFloat = 10
let radius: CGFloat = 2
let borderWidth: CGFloat = 1

override init() {
super.init()


}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.borderWidth = borderWidth
//self.layer.borderColor = UIColor(netHex:0xe5e5e5).CGColor
self.layer.cornerRadius = radius
self.delegate = self
}

// placeholder position
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds , inset , inset)
}

// text position
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds , inset , inset)
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true

}


}

Here is the code, I found some answers that say setting delegate of the textfield to itself is not a good idea, but they didn't tell what is good idea. Can you please help me on this issue?

I need this three function behavior for all the textFields, what is the correct way to do it?

Answer

Set the delegate to the view controller that uses the textfield not in your subclass.

textfield.delegate = self //self == view controller;

Remember to register your view controller as a delegate and add the delegate methods to your view controller's implementation file.