ios - AddObserver on UILabel not working -
i trying notifications whenever text changes in uilabel can resize fit new text. here code:
public class messagecontainer : uilabel { private readonly int _width; public messagecontainer(int width) { _width = width; textalignment = uitextalignment.center; font = uifont.preferredtitle1; textcolor = uicolor.white; lines = 999; this.addobserver("text", foundation.nskeyvalueobservingoptions.initial | foundation.nskeyvalueobservingoptions.new, textchanged); } private void textchanged(foundation.nsobservedchange change) { var s = change.newvalue foundation.nsstring; if (s != null) // s null here { var size = s.stringsize(uifont.preferredtitle1, new cgsize(_width - 20, 999), uilinebreakmode.characterwrap); this.resizeframe(size.width, size.height); } } } my textchanged function gets called, change.newvalue null. using xamarin.ios, i'm sure answer same in objective-c or swift.
here simple subclass uilabel delegate tell when text changes:
class mylabel: uilabel { var delegate: mylabeldelegate? override var text: string { willset(string) { delegate?.willset(self, text: string) } } } protocol mylabeldelegate { func willset(_ label: mylabel, text: string) } i did on phone, it’s not tested, should work.
Comments
Post a Comment