Godfather
Godfather

Reputation: 4330

Modify the value overriding a property willSet get/set

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?

Upvotes: 4

Views: 2339

Answers (2)

DiscDev
DiscDev

Reputation: 39052

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
        }
    }
}

Upvotes: 1

Daniel Krom
Daniel Krom

Reputation: 10058

use super

override var text: String? {
    get { return super.text }
    set(v){  super.text = v }
}

Upvotes: 6

Related Questions