user12345 user12345 - 5 months ago 37
Swift Question

Making custom UILabel using swift in iOS having frame issues

I want to create my own custom UILabel using swift and I'm running into frame issues when using the init super class.

This is what I had before:

let label = UILabel()


I used to basically use a normal UILabel. Firstly my question is, how is the frame set for this? Because when I step inside the UILabel class it inherits from UIView and the init method inside UIView takes a frame. So how is this frame created?

This then brings me to my own custom UILabel, which I have called TimeLabel. Here is its implementation:

class TimeLabel: UILabel {

var clientName: String?
var time: Time?

init(name:String, time:Time) {
self.clientName = name
self.time = time
super.init(frame: ??)
}

required init?(coder aDecoder: NSCoder) {
super.init(frame:??)
}
}


This now links to the first question, where should I be getting this frame from? I wasn't providing a frame before when calling UILabel? How should I deal with this?

Answer

If you don't want to provide a frame at initialization time, use CGRect.zero:

class TimeLabel: UILabel {
    var clientName: String?
    var time: Time?

    init(name:String, time:Time) {
        self.clientName = name
        self.time = time
        super.init(frame: CGRect.zero)
    }
}

You can always change the frame later, or use auto-layout and the frame will be set for you.

Your init(coder:) method should only decode your subclass' properties (if you want), and should leave everything else to the superclass:

    required init?(coder aDecoder: NSCoder) {
        // decode clientName and time if you want
        super.init(coder: aDecoder)
    }