Objective-C 中的宏未按要求工作

Macro not working as required in Objective-C

我有一个宏,很简单的一个,但我不明白问题在哪里?我收到错误:

"Expected ; after expression"

这是一个宏定义:

#define SEGCONTROL (itemArray, segmentedControl)      \
segmentedControl = [[SuperSegmentedControll alloc] initWithItems:itemArray];                                        \
segmentedControl.frame = CGRectMake(0, 0, 60, 28);     \
segmentedControl.layer.cornerRadius = 05;              \
[segmentedControl setTintColor:[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:102.0/255.0 alpha:1]];                  \
segmentedControl.backgroundColor = [UIColor colorWithRed:19.0/255.0 green:62.0/255.0 blue:137.0/255.0 alpha:1];              [segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];                                \
[segmentedControl setTitleTextAttributes:               @{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected]; \

我打电话如下:

 NSArray *itemArray = [NSArray arrayWithObjects: @"Save", nil];
 SuperSegmentedControll *segmentedControl;
 SEGCONTROL(itemArray, segmentedControl);

我想创建与在许多地方使用的类似代码相同的宏。为了保存,取消ETC。

失败的原因是 #define 宏名称 SEGCONTROL 和参数列表 (itemArray, segmentedControl) 之间有一个 space。这实质上是将 SEGCONTROL 定义为 (itemArray, segmentedControl) 而不是代码片段。要解决此问题,只需删除 SEGCONTROL

之后的 space
#define SEGCONTROL(itemArray, segmentedControl) \ ...

但是我强烈建议反对使用这种方法,而是在您的SuperSegmentedControll class(这反过来可能应该有一个 L 和一个更具描述性的名称)来设置控件。这样您将获得更好的编译器检查。像这样:

@implementation SuperSegmentedControl

- (instancetype)initWithItems:(NSArray *)items {
    self = [super initWithItems:items];
    if (self) {
        self.frame = CGRectMake(0, 0, 60, 28);
        self.layer.cornerRadius = 05;
        [self setTintColor:[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:102.0/255.0 alpha:1]];
        self.backgroundColor = [UIColor colorWithRed:19.0/255.0 green:62.0/255.0 blue:137.0/255.0 alpha:1];
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    }
    return self;
}

@end

将按如下方式使用:

NSArray *itemArray = [NSArray arrayWithObjects: @"Save", nil];
SuperSegmentedControl *segmentedControl = [[SuperSegmentedControl alloc] initWithItems:itemArray];