我想将自定义UIView添加到主视图中。
我想使用initWithTitle:description函数:
AchievementView *achievement = [[AchievementView alloc] initWithTitle:@"Test" description:@"The Descr"]];
但这是行不通的。必须将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];
最佳答案
您有两个问题:如何初始化视图以及如何将其添加到屏幕。
您可以使用initWithTitle:description:
方法,您只需要在类的实例上使用它,而不是在类本身上使用:
[[AchievementView alloc] initWithTitle:@"Test" description:@"The Descr"]];
您正确地认为您在
self
调用中输入了错误的addSubview
。您需要引用父视图。您可以将其传递到您的AchievementView
类中,但是在类外部进行管理比较干净。我还注意到
AchievementView
是UIView
的子类,但是您正在其中创建另一个UIView
。直接使用AchievementView
会更简单。您的代码应类似于以下内容:AchievementView.h
@interface AchievementView : UIView
@property (strong) NSString *achievementTtl;
@property (strong) NSString *achievementDescr;
- (id)initWithTitle:(NSString*)achievementTitle description:(NSString*)achievementDescription;
@end
AchievementView.m
- (id)initWithTitle:(NSString*)achievementTitle description:(NSString*)achievementDescription {
if (self = [super initWithFrame:CGRectMake(0, 0, 300, 423)]) {
self.achievementTtl = achievementTitle;
self.achievementDescr = achievementDescription;
self.layer.cornerRadius = 8;
self.layer.masksToBounds = YES;
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = .15;
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
主视图
- (IBAction)share:(id)sender {
AchievementView *achievement = [[AchievementView alloc] initWithTitle:@"Test" description:@"TestDEscr"];
[self.view addSubview:achievement];
}