ios - 宏无法按Objective-C的要求工作

标签 ios objective-c macros

我有一个宏,非常简单,但是我不明白问题出在哪里?我收到错误消息:

“预期;表达后”

这是一个宏定义:

#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/

相关文章:

c++ - iOS didFailToConnectPeripheral : with error Code=0 "Unknown error."

iphone - 应用发布到Appstore后图像消失

ios - 如何为 UICollectionView 实现放大/缩小动画

ios - 如何在ios应用程序中检测微笑

ios - UICollectionView 上的奇怪细胞 react

c - 宏扩展和字符串化 : How to get the macro name (not its value) stringified using another macro?

c++ - 包含头文件后,先前定义的宏消失了

vim - 一种在 vim 中第一个和最后一个非白字之间居中文本的简单方法?

iphone - 使 NavigationBar Title 与上一个 View 中选择的表格单元格相同

objective-c - NSManagedObject 的 NSPasteboard 类型