【问题标题】:iOS Child Views, SRP and custom eventsiOS 子视图、SRP 和自定义事件
【发布时间】:2011-12-11 10:38:42
【问题描述】:

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

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

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

//约翰

【问题讨论】:

    标签: objective-c events ios5 views single-responsibility-principle


    【解决方案1】:

    为了获取 xib 文件的内容,您必须先加载它,然后将 loadNibNamed:owner:options: 消息发送到 NSBundle 类。

    假设您有一个名为 CustomView 的 UIView 子类和 CustomView.xib 文件。在 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
    

    这是关于如何为您的自定义 UIView 子类使用 .xibs。如果您的应用类似于聊天,那么您必须以编程方式添加它们。

    至于在两个自定义视图之间发送消息的最佳方式,您必须在每个视图中创建对彼此的弱引用。

    合二为一

    @property (nonatomic, assign) CustomView *customView;
    

    在另一个

    @property (nonatomic, assign) AnotherCustomView *anotherCustomView;
    

    甚至在发生某些事情时向他们发送消息

    - (void)buttonPressed {
      [customView handleButtonPressedEvent];
    }
    

    让我知道这是否清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多