vimal prakash vimal prakash - 2 years ago 147
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() {


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 {
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download