0

我是 iOS 开发的新手,需要一些建议。我有一个聊天之类的应用程序。UI 应该有一个用于向服务器发布新消息的子视图和一个用于在表格视图中查看消息的子视图。

我在 Interface Builder 中将两个子视图都构建为 XIB:s。但我不确定如何在主视图控制器上使用这些。我可以使用 IB 将我的自定义视图添加到设计图面吗?还是我需要以编程方式添加这些?

在这两个子视图之间发送消息或自定义事件的最佳方式是什么?我想让它们尽可能地分离。大多数情况下,我想在用户登录或注销时发送一个事件,以便 UI 可以对这些更改做出反应。我还希望带有消息的表格视图知道何时从写入视图发布新消息。

//约翰

4

1 回答 1

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];
}

让我知道这是否清楚。

于 2011-12-11T11:18:20.557 回答