我是iOS开发的新手,需要一些建议。我有一个像应用程序聊天。 UI应具有用于向服务器发布新消息的子视图和用于在表视图中查看消息的一个子视图。
我在Interface Builder中将两个子视图构建为XIB:s。但我不确定如何在主视图控制器上使用它们。我可以使用IB将自定义视图添加到设计图面吗?或者我需要以编程方式添加这些?
在这两个子视图之间发送消息或自定义事件的最佳方法是什么?我想让它们尽可能脱钩。大多数情况下,我想在用户登录或注销时发送事件,以便UI可以对这些更改做出反应。我也喜欢带有消息的表视图,以了解何时从写入视图发布新消息。
// Johan
答案 0 :(得分:1)
为了获取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];
}
请告诉我这是否清楚。