2014-11-25 37 views
0

我想重写低于对象的C代码来迅速我怎样才能在迅速

- (NSArray *)rightButtons 
{ 
    NSMutableArray *rightUtilityButtons = [NSMutableArray new]; 
    [rightUtilityButtons sw_addUtilityButtonWithColor: 
    [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0] 
              title:@"More"]; 
    [rightUtilityButtons sw_addUtilityButtonWithColor: 
    [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f] 
              title:@"Delete"]; 

    return rightUtilityButtons; 
} 

sw_addUtilityButtonWithColor重写这个ObjC方法“rightButtons”如下定义:

#import "NSMutableArray+SWUtilityButtons.h" 

@implementation NSMutableArray (SWUtilityButtons) 

- (void)sw_addUtilityButtonWithColor:(UIColor *)color title:(NSString *)title 
{ 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.backgroundColor = color; 
    [button setTitle:title forState:UIControlStateNormal]; 
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    [button.titleLabel setAdjustsFontSizeToFitWidth:YES]; 
    [self addObject:button]; 
} 

尤其是头文件名称有一个“+”标记,我如何初始化“NSMutableArray + SWUtilityButtons.h”的实例?

回答

1

够简单。在斯威夫特添加扩展这样

extension NSMutableArray 
{ 

func sw_addUtilityButtonWithColor(color : UIColor, title : String) 
    { 
     var button:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton 
     button.backgroundColor = color; 
     button.setTitleColor(UIColor.whiteColor(), forState: .Normal) 
     button.setTitle(title, forState: .Normal) 
     button.titleLabel?.adjustsFontSizeToFitWidth; 
     self.addObject(button) 
    } 
} 

扩展可以从项目中的任何地方进行访问。您不需要像Objective-C中的类别那样导入。所以就这样使用

var rightUtilityButtons : NSMutableArray = NSMutableArray() 
rightUtilityButtons.sw_addUtilityButtonWithColor(UIColor.redColor(), title: "More")