在显示UIAlertView之前检查消息是否为空

时间:2013-07-29 10:22:33

标签: ios uialertview

UIAlertView广泛用于代码中。

我想在显示之前检查所有警报视图消息。

我在UIAlertView类别中编写了一个方法。

问题:

  • 有没有办法在一个地方修复此问题,所有alertview会在显示之前自动调用它。 (例如 - 重写一些方法)

注意 - 我已经有了一个方法,但我不想在所有地方手动更改代码,而是我正在寻找一个时尚的解决方案,如果可能的话,我在一个地方改变(如覆盖方法)

1 个答案:

答案 0 :(得分:1)

在UIAlertView上创建一个类别,并提供一种方法,首先检查消息是否存在,然后显示:

@implementation UIAlertView (OnlyShowIfMessageExists)

- (void)override_show
{
    if(self.message.length)
    {
        [self override_show];
    }
}

它正在调用override_show而不显示,因为这些方法将被调整。

在类别中实现+(void)加载方法,并使用show方法调整方法:

+(void)load
{
    SEL origSel = @selector(show);
    SEL overrideSel = @selector(override_show);

    Method origMethod = class_getInstanceMethod(UIAlertView.class, origSel);
    Method overrideMethod = class_getInstanceMethod(UIAlertView.class, overrideSel);

    if(class_addMethod(UIAlertView.class, origSel, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod)))
    {
        class_replaceMethod(UIAlertView.class, overrideSel, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    }
    else
    {
        method_exchangeImplementations(origMethod, overrideMethod);
    }
}

@end

现在,所有在UIAlertView上显示的调用都将使用您的方法override_show。

http://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html

相关问题