我试图在我的UILabel中的文本更改时收到通知,以便我可以调整它以适应新文本。这里是我的代码:UILabel上的AddObserver无法正常工作
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 as Foundation.NSString;
if (s != null) // s is always null here
{
var size = s.StringSize(UIFont.PreferredTitle1, new CGSize(_width - 20, 999), UILineBreakMode.CharacterWrap);
this.ResizeFrame(size.Width, size.Height);
}
}
}
我TextChanged
函数被调用,但change.NewValue
始终为空。我正在使用Xamarin.iOS,但我确定在Objective-C或Swift中的答案是一样的。
这工作。我甚至不知道我可以重写属性! – Darius