
[英]How to find text of UILabel which is set in Interface Builder?
[英]How should I be watching changes to UILabel's text when set in Interface Builder?
我正在构建一个UILabel库,该库主要旨在以编程方式使用,但我也希望它也可以与Interface Builder一起使用。 当用户在UILabel
子类上调用setText
时,我在那里观看并根据标签的使用更新了文本,但是IB似乎没有调用它。
我应该只是看awakeFromNib
吗?
如果是这样,则-awakeFromNib
-initWithCoder:
是首选位置,而-awakeFromNib
仍然可以如@KhanhNguyen所述使用。
问题变成如何找到我的UILabel
? 这是使用-viewWithTag:
的可能答案-viewWithTag:
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
[self registerKVO:[self viewWithTag:1]
forKeyPath:NSStringFromSelector(@selector(text))];
}
return self;
}
注意 - (instancetype)initWithCoder:(NSCoder *)aDecoder
不是将KVO安装在UIViewController中的正确位置,因为该视图尚未加载且也没有标签。
使用典型的参考插座注册KVO
- (void)viewDidLoad {
[super viewDidLoad];
[self registerKVO:self.label
forKeyPath:NSStringFromSelector(@selector(text))];
}
无论采用哪种方法,对KVO的响应都如下所示:
#pragma mark - NSObject(NSKeyValueObserving)
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(text))]) {
NSLog(@"%@",change[NSKeyValueChangeNewKey]);
}
}
...这样的设置和拆卸:
- (void)registerKVO:(NSObject *)object forKeyPath:(NSString *)keypath {
[object addObserver:self
forKeyPath:keypath
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void)dealloc {
[self removeObserver:self forKeyPath:NSStringFromSelector(@selector(text))];
#if !__has_feature(objc_arc)
[super dealloc];
#endif
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.