【发布时间】:2013-03-02 14:29:39
【问题描述】:
我知道以前有人问过这个问题,但答案相互矛盾,我很困惑,所以请不要喷我。
我希望在我的应用程序中拥有一个可重用的 UIView 子类。我想用一个 nib 文件来描述接口。
现在假设它是一个加载指示器视图,其中包含一个活动指示器。我想在某个事件上实例化这个视图并动画到视图控制器的视图中。我可以毫无问题地以编程方式描述视图的界面,以编程方式创建元素并在 init 方法中设置它们的框架等。
我怎样才能使用笔尖做到这一点?无需设置框架即可保持界面生成器中给定的大小。
我已经设法做到了,但我确定这是错误的(它只是一个带有选择器的视图):
- (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;
}
但我正在覆盖 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 初始化方法中设置笔尖吗?还是我做的没问题?
【问题讨论】:
-
但是第一行代码不是和你在
initWithDataSource的原始问题中使用的几乎一样吗?无论如何,即使您将所有者指定为“Nil”,这也将起作用。 -
值得注意的是,如今在 99.99999% 的情况下,人们只会使用 容器视图,它们现在无处不在,并且始终在 iOS 中使用。 how-to article
-
旁注,您可以将 [NSString stringWithFormat:@"%@",[FSASelectView class]] 替换为 NSStringFromClass([FSASelectView class])
标签: iphone ios objective-c uiview xib