Milap Jhumkhawala Milap Jhumkhawala - 4 months ago 18
iOS Question

Inherit properties of a UITextfield

I am new to Swift programming and I have a few textfields with similar properties. Can I create one textfield with defined properties and then extend them to other textfields.

num
inherits properties like
borderColor
and
borderWidth
from
textfield1
.

class TextElement: UITextField {
var textfiedl1: UITextField = UITextField(frame:CGRectMake(38,383,299,44))
textfield1.layer.borderColor = UIColor.grayColor().CGColor
textfield1.layer.borderWidth = 1.0
}


class TextElement2 : UITextField {
var num: TextElement = TextElement(frame: CGRectMake(38,416,299,44))
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
num.backgroundColor = UIColor.redColor()
self.addSubview(num)
}


This does not give any output. The simulator screen is blank. Any solution for this.

Answer

This is completely off the top of my head (not tested) but I think you want something along the lines of the following:

Base Class:

class BaseTextField: UITextField {

    init() {
        super.init(frame: CGRectZero)
        self.layer.borderColor = UIColor.grayColor().CGColor
        self.layer.borderWidth = 1.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Sub Class:

class YourTextField: BaseTextField {

    init(frame: CGRect, backgroundColor: UIColor) {
        super.init()
        self.frame = frame
        self.backgroundColor = backgroundColor
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Usage in Viewcontroller:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = YourTextField(frame: CGRectMake(38, 416, 299, 44), backgroundColor: UIColor.redColor())
        self.view.addSubview(textField)
    }

}

Note:

You probably want to actually do something in required init?(coder aDecoder: NSCoder) but for here I left the default implementation.

Comments