Home Methods related to UILabel drawing/appearing on screen
Reply: 2

Methods related to UILabel drawing/appearing on screen

Zubair
1#
Zubair Published in 2018-02-14 07:03:08Z

I'm new to iOS development so help me out here, I know iOS provides methods related to UIViews when then appear on screen, ViewWillAppear & ViewDidAppear, does iOS also provide such type of methods for UILabel too? I want to set my custom alignment to all the labels used in my app, when they appear on screen, so I want to do it using extension, would it be possible ?

Reinier Melian
2#
Reinier Melian Reply to 2018-02-14 07:32:00Z

First thing first, ViewWillAppear and ViewDidAppear are not the methods of UIView, these are the methods of UIViewController's lifecycle. UIView has methods like layoutSubviews and draw(_ rect: CGRect) which you can override to provide your own implementation for the UIView. Now UILabel is a subclass of UIView, so you can use these methods for your UILabel. What you want to do is to make a custom class which will inherit from UILabel, and override layoutSubviews or draw(_ rect: CGRect) method to provide your required CGRect. And then use that custom label throughout your app. Here's an example of how you can achieve this.

class CustomLabel: UILabel {

    override func layoutSubviews()
    {
         super.layoutSubviews()
         //change your frame here according to your needs.
    }
}
`
Reinier Melian
3#
Reinier Melian Reply to 2018-02-14 07:21:26Z

You can subclass UILabel and in your CustomUILabel in layoutSubviews method you can set the textAlignment

import UIKit

@IBDesignable class LeftAlignedUILabel: UILabel {

    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()
        setup()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setup()
    }


    func setup(){
        textAlignment = .left
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334384 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO