gpt4 book ai didi

ios - 将 UIColor 值分配给宏

转载 作者:行者123 更新时间:2023-11-28 18:57:51 25 4
gpt4 key购买 nike

这个问题指的是这篇 SO 帖子:How to set global variable with UIColor class

接受的答案建议像这样定义一个宏:

AppDelegate header :

// AppDelegate.h
#import <UIKit/UIKit.h>

#define black = [UIColor blackColor]
#define myColor = [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end

ViewController 实现:

// ViewController.m
#import "AppDelegate.h"
#import "ViewController.h"

@implementation ViewController

- (void) viewDidLoad {
[super viewDidLoad];

...

// they both give the same error,
// with or without semi-colons
// self.view.backgroundColor = black;
self.view.backgroundColor = myColor;

}

@end

但是,Xcode 不断弹出这两个异常:

预期表达

表达式不可赋值

我看过其他使用方法的建议,但这种方法最符合我的要求。

这可能是什么原因造成的?

最佳答案

在此上下文中要理解的关键是预处理器宏仅在编译时替换(实际上,1 对 1 替换)宏的代码,因此您的错误生成代码对于编译器实际上看起来像这样:

self.view.backgroundColor = = [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f];

你自己可以看出这没有意义!

当您定义要使用的宏时,请务必删除赋值运算符 (=):

#define black [UIColor blackColor]
#define myColor [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]

然后替换宏名称 myColor 实际上会向编译器提供所需的结果:

self.view.backgroundColor = [UIColor colorWithRed:(238.0f/255.0f) green:(251.0f/255.0f) blue:(255.0f/255.0f) alpha:0.8f]; // myColor has been replaced with the content of the macro

关于ios - 将 UIColor 值分配给宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30394151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com