Eri*_*ner 3 overriding objective-c objective-c-category
我想通过类似UIButtonType的UIButton类添加一个新的自定义:
enum {
UIButtonTypeMatteWhiteBordered = 0x100
};
@interface UIButton (Custom)
+ (id)buttonWithType:(UIButtonType)buttonType;
@end
Run Code Online (Sandbox Code Playgroud)
是否有可能以super某种方式获得该重写方法的实现?
+ (id)buttonWithType:(UIButtonType)buttonType {
return [super buttonWithType:buttonType];
}
Run Code Online (Sandbox Code Playgroud)
上面的代码无效,因为在此上下文中super引用UIControl.
您可以在运行时使用自己的自定义方法替换方法,如下所示:
#import <objc/runtime.h>
@implementation UIButton(Custom)
// At runtime this method will be called as buttonWithType:
+ (id)customButtonWithType:(UIButtonType)buttonType
{
// ---Add in custom code here---
// This line at runtime does not go into an infinite loop
// because it will call the real method instead of ours.
return [self customButtonWithType:buttonType];
}
// Swaps our custom implementation with the default one
// +load is called when a class is loaded into the system
+ (void) load
{
SEL origSel = @selector(buttonWithType:);
SEL newSel = @selector(customButtonWithType:);
Class buttonClass = [UIButton class];
Method origMethod = class_getInstanceMethod(buttonClass, origSel);
Method newMethod = class_getInstanceMethod(buttonClass, newSel);
method_exchangeImplementations(origMethod, newMethod);
}
Run Code Online (Sandbox Code Playgroud)
请注意如何使用它,请记住它取代了您的应用使用的每个UIButton的默认实现.此外,它确实覆盖+加载,因此它可能不适用于已经具有+ load方法并依赖它的类.
在你的情况下,你可能最好只是继承UIButton.
编辑:正如Tyler在下面所说,因为你必须使用类级方法来创建一个按钮,这可能是覆盖创建的唯一方法.
| 归档时间: |
|
| 查看次数: |
3458 次 |
| 最近记录: |