UILabel上的AddObserver无法正常工作

时间:2017-08-15 15:53:25

标签: ios xamarin.ios

我试图在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-C或Swift中答案是一样的。

2 个答案:

答案 0 :(得分:2)

这是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)
}

我在手机上做了这个,所以它没有经过测试,但它应该可行。

答案 1 :(得分:1)

您无法使用键值观察;相反,你需要子类化UILabel并检测文本的设置时间。

但是,我觉得你需要这个有点惊讶,因为你怎么能知道标签的文字何时发生变化?可能发生的唯一方法是改变了它。此外,UILabel在自动布局下自动调整大小,因此很难看出问题应该是什么。它“按照你想要的方式工作”。