2015-03-03 107 views
1

我想要繼承UIImage,所以我可以包括一個特殊的標題和其他信息,我需要爲每個圖像。下面是我的.m:嘗試子類UIImage,但圖像不顯示在圖像視圖

#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

您不應該爲此嘗試繼承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需要一個完整的路徑不只是文件名。

+0

爲什麼它不好繼承UIImage? – Kex 2015-03-03 13:58:10

+0

它並不總是壞,但在這種情況下,如果UIImage只是一個像素集合問自己,爲什麼UIImage應該知道標題,specialMessage和neededCount?我看不到在UIImage中添加這些信息的正當理由。 – 2015-03-03 14:15:42

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") 
    } 

} 
相關問題