2

I would like to add a white space in front of any given text of a UILabel.

I thought that I could extend the UILabel-class as follows:

class UILabel_iKK: UILabel {

    override var text: String? {
        didSet {
            if let txt = self.text {
                self.text = " " + txt
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

But obviously this leads to an endless loop (i.e. text change causes didSet to fire again and again.

What would be another way of doing this in a most elegant way ?

iKK
  • 6,394
  • 10
  • 58
  • 131

3 Answers3

3

Yes, it's possible. Although I don't like it, the following code won't loop forever:

didSet {
  if let txt = self.text, txt.first != " " {
    self.text = " " + txt
  }
}
mugx
  • 9,869
  • 3
  • 43
  • 55
2

This should work

class Label_iKK: UILabel {

    override var text: String? {
        set(value) {
            if let txt = value {
                super.text = " " + txt
            }
        }
        get {
            return super.text
        }
    }
}
adamfowlerphoto
  • 2,708
  • 1
  • 11
  • 24
  • Thank you, both Andrea and Spads, for your help ! I somehow prefer Spads idea for implementation since it seems more generic in a way. – iKK Dec 20 '17 at 15:58
0

Thank you both, Andrea and Spads, for you ideas!

I have added the empty-String addition in the reading-part - since I only want to have the additional white-spaces inside the Label upon seeing it in the UI (but not as actual value when dealing with it in code !)...

class UILabel_iKK: UILabel {

    var myText: String? = ""

    override var text: String? {
        get {
            if let txt = super.text {
                if txt.count >= 3 {
                    return String(txt[3...])
                } else {
                    return super.text
                }
            } else {
                return super.text
            }
        }
        set(value) {
        if let txt = value {
            super.text = "   " + txt   // 3 white-spaces added here...
            }
        }
    }
}
iKK
  • 6,394
  • 10
  • 58
  • 131