我知道之前有人问过这个问题,但答案相互矛盾,我很困惑,所以请不要喷我。
我想在我的应用程序中拥有一个可重用的 UIView
子类。我想用一个 nib 文件来描述接口(interface)。
现在假设它是一个加载指示器 View ,其中包含一个事件指示器。我想在某个事件上实例化这个 View 并动画到 View Controller 的 View 中。我可以毫无问题地以编程方式描述 View 的界面,以编程方式创建元素并在 init 方法中设置它们的框架等。
我怎样才能使用 Nib 做到这一点?无需设置框架即可保持界面生成器中给定的大小。
我已经设法做到了,但我确定这是错误的(它只是一个带有选择器的 View ):
- (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 获取它。
编辑:我想在 View Controller 中创建这个自定义 View ,并有权控制 View 的元素。我不想要新的 View Controller 。
谢谢
编辑:我不知道这是否是最佳做法,我确定不是,但我就是这样做的:
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) {
}];
仍然需要正确的做法
是否应该使用 View Controller 和带有 nib 名称的初始化来完成?我应该在代码中的一些 UIView 初始化方法中设置 Nib 吗?还是我做的没问题?
最佳答案
MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]
我正在使用它来初始化我拥有的可重用自定义 View 。
请注意,您可以在最后使用 "firstObject",这样会更简洁一些。 "firstObject"是 NSArray 和 NSMutableArray 的一个方便的方法。
这是一个典型的示例,加载 xib 以用作表头。在你的文件 YourClass.m
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}
通常,在 TopArea.xib
中,您会单击 File Owner 并将文件所有者设置为 YourClass。然后实际上 在 YourClass.h 你会有 IBOutlet 属性。在 TopArea.xib
中,您可以将控件拖到这些 socket 上。
不要忘记在 TopArea.xib
中,您可能必须单击 View 本身并将其拖到某个 socket ,以便您可以控制它,如有必要。 (一个非常有值(value)的提示是,当您对表格单元格行执行此操作时,您绝对必须这样做 - 您必须将 View 本身连接到代码中的相关属性。)
关于iphone - 为 UIView 子类加载 Nib 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15405916/