我知道这个问题以前已经被问过了,但答案是矛盾的,我感到困惑,所以请不要抨击我。
我想在整个应用程序中拥有可重用的UIView
子类。我想使用一个nib文件来描述接口。
现在假设它是一个带有活动指示器的加载指示器视图。我想在某些事件上实例化此视图并将其动画化到视图控制器的视图中。我可以很容易地通过编程方式描述视图的接口,创建元素并在init方法中设置它们的框架等。
但如何使用nib呢?保持界面构建器中给定的大小而无需设置框架。
我已经设法像这样做了,但我确定这是错误的(它只是一个带有选择器的视图):
- (id)initWithDataSource:(NSDictionary *)dataSource {
self = [super init];
if (self){
self = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", [self class]] owner:self options:nil] objectAtIndex:0];
self.pickerViewData = dataSource;
[self configurePickerView];
}
return self;
}
但是我正在覆盖自己,当我实例化它时:
FSASelectView *selectView = [[FSASelectView alloc] initWithDataSource:selectViewDictionary];
selectView.delegate = self;
selectView.frame = CGRectMake(0, self.view.bottom + 50, [FSASelectView width], [FSASelectView height]);
我需要手动设置框架而不是从IB中获取。
编辑:我想在视图控制器中创建此自定义视图,并可以访问控制视图的元素。我不想要一个新的视图控制器。
谢谢
编辑:我不知道这是否是最佳实践,我确定不是,但这是我的做法:
FSASelectView *selectView = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@",[FSASelectView class]] owner:self options:nil] objectAtIndex:0];
selectView.delegate = self;
[selectView configurePickerViewWithData:ds];
selectView.frame = CGRectMake(0, self.view.bottom + 50, selectView.width, selectView.height);
selectView.alpha = 0.9;
[self.view addSubview:selectView];
[UIView animateWithDuration: 0.25 delay: 0 options:UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionCurveEaseInOut animations:^{
selectView.frame = CGRectMake(0, self.view.bottom - selectView.height, selectView.width, selectView.height);
selectView.alpha = 1;
} completion:^(BOOL finished) {
}];
正确的做法仍然需要
这个操作应该使用视图控制器和nib名称进行初始化吗?我应该在代码中的某个UIView初始化方法中设置nib吗?还是我所做的方式可以接受?