我有一个宏,非常简单,但是我不明白问题出在哪里?我收到错误消息:
“预期;表达后”
这是一个宏定义:
#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)
之间存在空格。这实际上是将SEGCONTROL
定义为(itemArray, segmentedControl)
而不是代码段。要解决此问题,只需删除SEGCONTROL
后的空格
#define SEGCONTROL(itemArray, segmentedControl) \ ...
但是,我强烈建议使用这种方法将反对,而不是在
SuperSegmentedControll
类上使用一个方法(该方法又应该有一个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];
关于ios - 宏无法按Objective-C的要求工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495550/