如何在swift中重写这个ObjC方法“rightButtons”

时间:2014-11-25 14:11:39

标签: swift

我想将下面的object-c代码重写为swift

- (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定义如下:

#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 个答案:

答案 0 :(得分:1)

足够简单。像Swift一样在

中添加扩展名
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")