【问题标题】:How to use colorLiteral, imageLiteral in objective c如何在objective c中使用colorLiteral、imageLiteral
【发布时间】:2019-10-07 12:50:47
【问题描述】:

我最近学习在 Xcode 11 中使用 colorLiteral 和 imageLiteral。它在我的 swift 文件中运行良好。如何在 Objective C 文件上使用 colorLiteral 和 imageLiteral?

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

【问题讨论】:

  • 我建议不要在所有户外游乐场使用它们,但我想这种观点并不常见。如果可能,使用颜色资源并按名称加载颜色,或者至少创建一个带有颜色常量的单独 UIColor 扩展。

标签: ios objective-c xcode


【解决方案1】:

参考

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];

【讨论】:

  • 作为您答案的补充:要使用您在 xcassets 文件夹中设置的颜色,您也可以使用 [UIColor colorNamed:@"colorNameHere"] 尽管仅适用于 iOS 11 及更高版本。
  • 我知道如何在 Objective C 中使用 set Color 和 Image。我只想通过使用 colorLiteral 和 imageLiteral 轻松更改值。我的解决方法是创建一个 swift 文件并将其导入到 Objective C 中。
【解决方案2】:

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

它们是 Swift 关键字

【讨论】:

    【解决方案3】:

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

    Utils.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 特性。

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2011-02-10
      • 2018-11-19
      • 2011-07-07
      • 2014-08-11
      相关资源
      最近更新 更多