我正在创建一个UIView子类(我称之为MarqueeLabel
),当UILabel文本对于包含视图来说太长时,它会以矩形方式为子视图UILabel ivar设置动画。
我希望有一个干净的实现,而不必在我的MarqueeLabel
类 中编写方法来设置/检索所有标准的UILabel(文本,字体,颜色等) )UILabel ivar的实例变量。我已经找到了一种通过消息转发执行此操作的方法 - 发送到MarqueeLabel
的所有无法识别的方法都会传递到UILabel ivar。在我的例子中,MarqueeLabel
无法识别的方法是UILabel通常使用的方法。
但这种方法存在一些问题:
1。您必须使用[marqueeLabel setText:@"Label here"]
,而不是marqueeLabel.text
2. 编译器会在上面的行中发出警告,因为:
'MarqueeLabel'可能无法响应'-setText:'
我会忽略但会惹恼其他人。
为了避免这些问题,有没有办法将这些方法“提出”到ivar中,以便在使用该类时可以访问这些方法,同时仍然对ivar对象起作用?
谢谢!
注意:我设置它的方式可能不是最好的方法。也许子类化或类继续UILabel会更好,但我无法掌握动画+剪辑(当文本滚动移出包含UIView并消失时)可以使用这些方法完成。
注2:我知道您可以使用marqueeLabel.subLabel.text
subLabel
是子视图UILabel。这可能是我采取的方向,但也可以看看是否有更好的解决方案!
答案 0 :(得分:1)
对于属性,您可以在接口中定义属性并在实现中使用@dynamic,这样您就不必创建存根实现。确保您还覆盖valueForUndefinedKey:
和setValue:forUndefinedKey:
并转发到您的标签。
对于不属于属性的任何方法,您可以使用类别来声明方法而不实现它。这将消除警告,但仍然使用内置转发。
//MarqueeLabel.h
#import <UIKit/UIKit.h>
@interface MarqueeLabel : UIView {}
@property (nonatomic, copy) NSString *text;
@end
@interface MarqueeLabel (UILabelWrapper)
- (void)methodToOverride;
@end
//MarqueeLabel.m
#import "MarqueeLabel.h"
@implementation MarqueeLabel
@dynamic text;
- (id)valueForUndefinedKey:(NSString *)key {
return [theLabel valueForKey:key];
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
[theLabel setValue:value forKey:key];
}
@end