1

I recently learn to use colorLiteral and imageLiteral in Xcode 11. It works fine in my swift file. How can I use colorLiteral and imageLiteral on Objective C file?

It seems Xcode does not support colorLiteral and imageLiteral for Objective C.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Kelvin Tan
  • 982
  • 1
  • 12
  • 33
  • I would recommend not to use them at all outside playgrounds but I guess this opinion is not so common. If possible, use color assets and load the color by name, or at least create a separate `UIColor` extension with color constants. – Sulthan Oct 07 '19 at 13:30

3 Answers3

2

You can't. These features are not available in Objective-C, only in Swift.

They are Swift Keywords

Scriptable
  • 19,402
  • 5
  • 56
  • 72
2

With reference

Objective-C does not support color literal and Image literal. Both introduce in Swift, early that

  • To use an image in Objective-C
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
  • For Color
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = lightGrayHeader;

If you want to use a static method on UIColor to fetch a colour, you could do this:

@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];
steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
  • As an addition to your answer: to use the colours you have set in the xcassets folder, you can also use `[UIColor colorNamed:@"colorNameHere"]` though only available for iOS 11 and up. – Bram Oct 07 '19 at 13:47
  • I know how to use set Color and Image in Objective C. I just want to easily change the value by using colorLiteral and imageLiteral. My workaround is to create a swift file and import it into Objective C. – Kelvin Tan Oct 07 '19 at 14:08
0

It turns out that that features are not available in Objective-C. My workaround is to create a swift file for imageLiteral and colorLiteral and imports them in objective c file.

Utils.swift

import UIKit

@objc class Utils: NSObject {



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

}

Objective C file:

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

That way I can take advantage of colorLiteral feature for Objective-C Project.

Kelvin Tan
  • 982
  • 1
  • 12
  • 33