我想將我的自定義UIView添加到我的主視圖。添加子視圖到具有子視圖類功能的主視圖
我想使用的功能initWithTitle:描述:喜歡:
AchievementView *achievement = [[AchievementView alloc] initWithTitle:@"Test" description:@"The Descr"]];
但是,這是行不通的。 t initWithTitle:description:函數必須作爲類方法實現。
AchievementView.h
@interface AchievementView : UIView
@property (strong) NSString *achievementTtl;
@property (strong) NSString *achievementDescr;
@property (strong) UIView *theAchievementView;
- (void)initWithTitle:(NSString*)achievementTitle description:(NSString*)achievementDescription;
- (void)showAchievement;
@end
AchievementView.m
-(void)initWithTitle:(NSString*)achievementTitle description:(NSString*)achievementDescription {
self.achievementTtl = achievementTitle;
self.achievementDescr = achievementDescription;
}
- (void)showAchievement {
// Create view popup
self.theAchievementView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 423)];
self.theAchievementView.layer.cornerRadius = 8;
self.theAchievementView.layer.masksToBounds = YES;
self.theAchievementView.layer.shadowRadius = 5;
self.theAchievementView.layer.shadowOpacity = .15;
[self.theAchievementView setBackgroundColor:[UIColor whiteColor]];
[self addSubview:self.theAchievementView];
}
呼叫在主視圖的方法:
- (IBAction)share:(id)sender {
AchievementView *achievement = [[AchievementView alloc] init];
achievement.achievementTtl = @"Test";
achievement.achievementDescr = @"TestDEscr";
[achievement showAchievement];
}
我不能與子視圖添加到主視圖這個功能。 我認爲「自我」是錯誤的。應該在那裏?
[self addSubview:self.theAchievementView];
你缺少'alloc'在你的代碼。它應該是'AchievementView * achievement = [[AchievementView alloc] initWithTitle ...' –
oops。我寫它只是爲了解釋,我想做什麼;) – Florian
我對你想要做的事情有點困惑。是所有這些代碼的插圖,還是真正的代碼?因爲如果它是真實的代碼,你的初始值必須是類方法,並且必須遵循某些約定,即, +(id)init ... {self = [super init]; if(self){/ * initialize stuff * /} return self; } 如果你不這樣做,自我將永遠爲空。 – Travis