Mel*_*emi 4 cocoa cocoa-touch objective-c uilabel
我想覆盖UILabel的setText方法,但我不确定:
A)这是可能的,
B)是否有更好的方法来实现我想要实现的目标.
我有一个子类,UIView它有一个UILabel属性作为其子视图之一.我想知道UILabel's"文本"属性何时更改,以便我可以调整其后面的圆角矩形的大小.如果我拥有,UILabel我只是覆盖setText...但是UILabelApple的,它的实现是隐藏的.
那么,我该怎么做呢?
not*_*oop 10
您可以使用Key-Value Observing跟踪UILabel.text属性的更改.该方法包括三个步骤:
1)加载视图时注册以观察属性
[label addObserver:inspector
forKeyPath:@"text"
options:(NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld)
context:NULL];
Run Code Online (Sandbox Code Playgroud)
2)收到有关任何变更的通知:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqual:@"text"]) {
// put your logic here
}
// be sure to call the super implementation
// if the superclass implements it
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
Run Code Online (Sandbox Code Playgroud)
3)当您不再感兴趣时,取消注册观察:
[label removeObserver:inspector forKeyPath:@"text"];
Run Code Online (Sandbox Code Playgroud)
Mat*_*man 10
UILabel的子类可以很容易地覆盖setText方法.我不确定为什么这个尚未被包含在这个4岁问题的合法答案中.
- (void) setText:(NSString *)text
{
[super setText:text];
[self sizeToFit];
}
Run Code Online (Sandbox Code Playgroud)
Matt的答案对于Objective-C是好的,但是在Swift中不起作用(正常,当他回答时它不存在),来自notnoop的公认答案确实很快,即使它更复杂,只是为了给另一个在swift中你可以使用didSet:
class MyLabel: UILabel {
override var text: String? {
didSet {
if let text = text {
println("the new text is: \(text)")
} else {
println("the text has been set to nil")
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8218 次 |
| 最近记录: |