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.
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.
You can't. These features are not available in Objective-C, only in Swift.
They are Swift Keywords
With reference
Objective-C does not support color literal
and Image literal
. Both introduce in Swift
, early that
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;
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];
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.