我正在尝试将UIImage子类化,因此我可以为每个图像添加一个特殊的标题和其他信息。下面是我的.m:
#import "Sticker.h"
@implementation Sticker
//custom init
-(instancetype)initWithTitle: (NSString *)title neededCount: (int)neededCount specialMesage: (NSString *)specialMesage andFilename: (NSString *)path {
self = [super initWithContentsOfFile:path];
if(self) {
self.title=title;
self.neededCount=neededCount;
self.specialMessage=specialMessage;
}
return self;
}
我有一个带有单个UIImageView的空视图控制器,我正在尝试创建一个新的贴纸对象并使用UIImageView中的图像。代码:
Sticker *sticker = [[Sticker alloc] initWithTitle:@"crazy clown" neededCount:50 specialMessage:@"stackoverflow" andFilename:@"clown"];
self.imageView.image=sticker;
self.imageView.hidden=NO;
由于某种原因,图像未显示且没有错误消息。 "小丑"是Images.xcassets中的pdf图像。谁能给我一些指示,告诉我为什么这不起作用?
答案 0 :(得分:0)
您不应该为此尝试创建一个具有UIImage属性的类来为UIImage创建子类。
@interface Sticker : NSObject
@property (strong, nonatomic) NSString *title;
@property (assign, nonatomic) int neededCount;
@property (strong, nonatomic) NSString *specialMessage;
@property (strong, nonatomic) UIImage *image;
-(instancetype)initWithTitle:(NSString *)title neededCount:(int)neededCount specialMesage:(NSString *)specialMessage filename:(NSString *)name;
@end
@implementation Sticker
-(instancetype)initWithTitle:(NSString *)title neededCount:(int)neededCount specialMesage:(NSString *)specialMessage filename:(NSString *)name {
if(self = [super init]) {
self.title = title;
self.neededCount = neededCount;
self.specialMessage = specialMessage;
self.image = [UIImage imageNamed:name];
}
return self;
}
@end
Sticker *sticker = [[Sticker alloc] initWithTitle:@"crazy clown" neededCount:50 specialMessage:@"stackoverflow" filename:@"clown"];
self.imageView.image = sticker.image;
无论如何initWithContentsOfFile
需要一个完整的路径而不仅仅是文件名。
答案 1 :(得分:0)
子类化UIImage有点时髦。但它可以做到
class PlaceHolderIcon: UIImage {
override init() {
let image = UIImage(named: "image-name")!
super.init(cgImage: image.cgImage!, scale: UIScreen.main.scale, orientation: .up)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required convenience init(imageLiteralResourceName name: String) {
fatalError("init(imageLiteralResourceName:) has not been implemented")
}
}