重写父类方法的两种实现方式

如果想重写一个类的方法,既可以通过继承该类(在这里就不多少了),还可以通过类别(类的扩展catologe) 方法;比如重写UIAlertView 的 layoutSubviews   这样类扩展是可以的:


但是, 这样会导致在同一个类里面用到的所有UIAlertView 都会重写这样的方法 ,导
@interface UIAlertView (helper) 
- (void)layoutSubviews;
 @end @implementation UIAlertView(helper) 
//layout 执行的顺序在 drawRect 之前
//在iOS 7 后,drawRect 和 layoutSubviews 不会自动执行,除非涉及到setFrame addView 等
//在iOS 5 中,此方法会被重复调用4次
- (void)layoutSubviews{
    if (iOSSEVEN) {
        return;
    }
    CGRect frame = self.frame;
    frame.size.height = frame.size.height + 50;
    frame.origin.y = frame.origin.y - 25;
    self.frame = frame;
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 6.0f) {
        for (UIView *view in self.subviews) {
            NSString *class = NSStringFromClass([view class]);
            if ([class isEqualToString:@"UIAlertSheetTextField"] || [class isEqualToString:@"UIThreePartImageView"] || [class isEqualToString:@"UIAlertButton"] ) {
                CGRect vFrame = view.frame;
                vFrame.origin.y = vFrame.origin.y + 50;
                view.frame = vFrame;
            }
        }
    }else{
       //5.0 - 6.0 系统, 在5.n 系统中,layoutSubviews 方法会被执行多次,所以选在静态修改frame
        int alertBtnIndex = 0;
        for (UIView *view in self.subviews) {
            NSString *class = NSStringFromClass([view class]);
            if ([class isEqualToString:@"UIAlertButton"] ) {
                if (alertBtnIndex == 0) {
                    view.frame = CGRectMake(11, 209, 262, 43);
                }else if (alertBtnIndex == 1){
                    view.frame = CGRectMake(11, 95, 262, 43);
                }else if (alertBtnIndex == 2){
                    view.frame = CGRectMake(11, 145, 262, 43);
                }
                alertBtnIndex ++;
            }else if ([class isEqualToString:@"UIThreePartImageView"]) {
                view.frame = CGRectMake(11, 50, 262, 31);
            }else if ([class isEqualToString:@"UIAlertSheetTextField"]){
                view.frame = CGRectMake(16, 50, 252, 31);
            }
        }
    }
}

@end




致代码的维护性是很差的!所以不建议用类别!如果非要用类别,建议用Object C 的关联给UIAlertVIew 关联一个属性来判断是不是应该重写此方法!

你可能感兴趣的:(继承,Objective-C)