Search code examples
iosobjective-cuilabelrubymotion

Subclassing UILabel in RubyMotion to set attributedText kerning


I need to support custom kerning for some of my labels that are being added through Interface Builder (IB). The custom class is set on the Label in IB and the text is set there as well. Attempting to override the text property with the attributedText property is not working.

This is working fine for my UIButton subclass, but a similar technique is not behaving with UILabel.

The attributedText property does not seem to have any affect when set in awakeFromNib or drawRect:rect.

Example

class KernedLabel < UILabel

  def awakeFromNib
    super

    attributed_text = NSMutableAttributedString.alloc
      .initWithString("Atributed Text")

    attributed_text.addAttribute(NSKernAttributeName,
                                 value: 1.0,
                                 range: [0, attributed_text.length])

    attributedText = attributed_text
  end

end

Solution

  • Your code works fine for me with one minor change: you need to use self.attributedText = (calling the method on self):

    def awakeFromNib
      super
    
      attributed_text = NSMutableAttributedString.alloc
        .initWithString("Atributed Text")
    
      attributed_text.addAttribute(NSKernAttributeName,
                                   value: 1.0,
                                   range: [0, attributed_text.length])
    
      self.attributedText = attributed_text
    end