每当我的 UILabel 中的文本发生更改时,我都会尝试获取通知,以便我可以调整它的大小以适应新文本。这是我的代码:
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 中是相同的。
最佳答案
这是 UILabel 的一个简单子(monad)类,它带有一个委托(delegate)来告诉您文本何时更改:
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)
}
我在手机上做了这个,所以它没有经过测试,但它应该可以工作。
关于ios - UILabel 上的 AddObserver 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45696605/