每当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总是为null。我正在使用Xamarin.iOS,但我确信在Objective或Swift中答案是相同的。
发布于 2017-08-15 16:35:07
下面是UILabel的一个简单子类,它有一个委托来告诉您文本何时更改:
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)
}我在手机上做的,所以没有测试,但应该能用。
发布于 2017-08-15 15:59:56
您不能为此使用键值观察;相反,您需要对UILabel进行子类化,并检测文本何时设置。
然而,我有点惊讶,你认为你需要这个,因为你怎么可能不知道什么时候标签的文字变化?唯一能发生的就是你改变了它。此外,在自动收费模式下,UILabel是自我调整的,所以很难看出问题是什么。它“只是起作用”的方式,你希望它。
https://stackoverflow.com/questions/45696605
复制相似问题