0

If I have an instance of UILabel in storyboard and I have it connected to view controller as IBOutlet. If I want add some functionality only to this label, how can I do it? I know that for obj-c you make a subclass of UILabel. But I wonder if there is better approach in swift.

Is it possible for this specific label to conform to some protocol that I'll make.

Karthick Selvaraj
  • 2,387
  • 17
  • 28
Klemen
  • 2,144
  • 2
  • 23
  • 31

2 Answers2

2

You can declare a private extension in the same file you're using the UILabel

private extension UILabel {}

In this case only the components in the same file can use the new feature. I know, it's a kind of workaround, but in my cases where I create a single file per each component, it works.

Pay attention that the protocol conformance has to be public, so you can't use the private access level

EDIT: since you need a special configuration for only one UILabel in a single file, this way won't allow it. Subclassing is the only solution

Luca D'Alberti
  • 4,749
  • 3
  • 25
  • 45
0

If I want add some functionality only to this label, how can I do it?

you can add functionality to an existing class using extensions:

extension UILabel {
    func foo() -> String{
        // this funtionality is availible on all UILabels now. 
        // You can also call self. Example:
        return self.text
    }
}

Find detailed information here.

shallowThought
  • 19,212
  • 9
  • 65
  • 112