Milap Jhumkhawala Milap Jhumkhawala - 1 year ago 100
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.

inherits properties like

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()

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

Answer Source

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) {
        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() {
        let textField = YourTextField(frame: CGRectMake(38, 416, 299, 44), backgroundColor: UIColor.redColor())



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

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