Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the value overriding a property willSet get/set

Tags:

ios

swift

I have a custom UILabel and I override it's text property. I need to modify the value of this property if upperCase = true and the problem is that I’m calling recursively the setter.

@IBDesignable class CustomLabel: UILabel {
@IBInspectable var upperCase: Bool = false
override var text: String? {
    willSet {
        if upperCase == true {
            text = newValue?.uppercaseString  
        }
    }
}
}

I also tried:

var aux: String?
override var text: String? {
    get { return aux }
    set {  aux = newValue }
}

But the text label is not set. Any suggestion?

like image 877
Godfather Avatar asked Mar 14 '23 21:03

Godfather


2 Answers

use super

override var text: String? {
    get { return super.text }
    set(v){  super.text = v }
}
like image 91
Daniel Krom Avatar answered Mar 17 '23 11:03

Daniel Krom


The selected answer shows you how to modify the text as it's being set, but it doesn't specifically address the question, which asked how to create a UILabel subclass that will automatically make the text uppercase.

Here's a UILabel subclass that will always be uppercase

import UIKit

class UppercaseLabel: UILabel{

    override var text: String?{
        get{
            return super.text
        }
        set(newText){
            super.text = newText?.uppercaseString
        }
    }
}
like image 33
DiscDev Avatar answered Mar 17 '23 10:03

DiscDev