2014-11-25 75 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")