为了获取 xib 文件的内容,您必须先加载它,然后将loadNibNamed:owner:options:
消息发送到 NSBundle 类。
假设您有一个名为 CustomView 和 CustomView.xib 文件的 UIView 子类。在 xib 文件中,每个视图都有一个标签。您的 .h 文件如下所示:
@interface CustomView : UIView
@property (nonatomic, assign) UILabel *someTextLabel; //use assign in order to not to override dealloc method
@end
.m
@implementation CustomView
- (id)init {
self = [super init];
if (self) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil];
[self addSubview:[topLevelObjects objectAtIndex:0]]; //this object is a CustomView.xib view
self.someTextLabel = (UILabel *)[self viewWithTag:5]; //consider you have a UILabel on CustomView.xib that has its tag set to 5
}
return self;
}
@end
这是关于如何将 .xibs 用于您的自定义 UIView 子类。如果您的应用程序类似于聊天,那么您必须以编程方式添加它们。
至于在两个自定义视图之间发送消息的最佳方式,您必须在每个视图中创建对彼此的弱引用。
在一个
@property (nonatomic, assign) CustomView *customView;
在另一个
@property (nonatomic, assign) AnotherCustomView *anotherCustomView;
甚至在发生某些事情时向他们发送消息
- (void)buttonPressed {
[customView handleButtonPressedEvent];
}
让我知道这是否清楚。