如何在目标 c 中使用颜色文字、图像文字



我最近学会了在 Xcode 11 中使用 colorLiteral 和 imageLiteral。它在我的 swift 文件中工作正常。如何在目标 C 文件上使用颜色文字和图像文字?

似乎 Xcode 不支持 Objective C 的 colorLiteral 和 imageLiteral。

你不能。这些功能在 Objective-C 中不可用,仅在 Swift 中可用。

它们是迅捷的关键词

参考

  • 如何将图像设置为 UIImage
  • 物镜 C 中的颜色变量

Objective-C 不支持color literalImage literal。两者都在Swift中介绍,早期

  • 在 Objective-C 中使用图像
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
  • 对于颜色
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = lightGrayHeader;

如果你想在UIColor上使用静态方法来获取colour,你可以这样做:

@interface UIColor (MyColours)
+ (instancetype)lightGrayHeader;
@end
@implementation UIColor (MyColours)
+ (instancetype)lightGrayHeader {
return [self  colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
}
@end
And then as long as you import the UIColor (MyColours) header, you could use:
self.view.backgroundColor = [UIColor lightGrayHeader];

事实证明,这些功能在 Objective-C 中不可用。 我的解决方法是为 imageLiteral 和 colorLiteral 创建一个 swift 文件,并将它们导入目标 c 文件中。

实用工具.swift

import UIKit
@objc class Utils: NSObject {

@objc var textColor = #colorLiteral(red: 0.5609482021, green: 1, blue: 0.3726723031, alpha: 1)
}

目标 C 文件:

Utils * utils = [Utils new];
label.textColor = utils.textColor;

这样我就可以利用Objective-C项目的colorLiteral功能。

最新更新