繁体   English   中英

如何将 XIB 子代的 UIView 与父 XIB 的 UIView 通信?

[英]How to communicate an UIView from a XIB child to an UIView from a parent XIB?

我想知道是否可以在从 XIB 文件加载的 UIView 内点击某处(或做其他事情)并从父 XIB 触发 UIView 的操作(例如更改父 UIC 中 ZA4F6654A7772842B01988CBFEC 的标题)。 这是NewsController class接口的代码片段:

#import <UIKit/UIKit.h>
#import "NewsPage.h"
@interface NewsController : UIViewController {
    // Some objects
    UIButton *loadButton;
    UIView *newsView;
    NewsPage *newsPage;
}
@property (nonatomic, retain) IBOutlet UIButton *loadButton;
@property (nonatomic, retain) IBOutlet UIView *newsView;
@property (nonatomic, retain) NewsPage *newsPage;
@end

这是 NewsPage 的 class 实现的片段,我在其中加载子 XIB:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Some code
    newsPage = [[NewsPage alloc] initWithNibName:@"NewsPage" bundle:nil];
    [newsView addSubview:newsPage.view];
    // Some other code
}

这是 NewsPage class 接口内的一段代码:

#import <UIKit/UIKit.h>
#import "NewsController.h"
@interface NewsPage : UIViewController {
    NewsController *newsController;
}
@property (nonatomic, retain) IBOutlet NewsController *newsController;
@end

这是 class 实现的片段

- (void)tapAction:(UIGestureRecognizer *)gestureRecognizer {
    // Some code
    NewsController *newsController = [[NewsController alloc] initWithNibName:@"News" bundle:nil];
    NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);        
    newsController.loadButton.titleLabel.text = @"New text goes here!";
    NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);
    // Some other code
}

使用此代码(并在 IB 中进行一些接线之后),我在调试器中看到了正确的标题,但模拟器不会更新标题更改。 我的猜测是子 UIViews 与父 UIViews 平行,即使我做了这样的事情:

[newsController.loadButton removeFromSuperview]

父 UIView 层次结构没有变化,因为子 UIViews “不在”父 UIView 的“内部”。 我希望有人可以帮助解决这个问题,因为这非常令人沮丧。 在此先感谢您。

我看到的一个问题是,您正在访问 NewsController 中的一些元素,这些元素可能尚未从 NIB 中解压缩,因为它们在需要视图时是懒惰地完成的。 在引用这些项目之前,尝试访问 controller 的 .view 成员,这应该强制加载。 这是一个似乎每个人都会遇到的问题,直到延迟加载的想法被理解。

NewsController *newsController = [[NewsController alloc] initWithNibName:@"News" bundle:nil];
newController.view; //hopefully this doens't get optimized out. If so, change it a bit.
NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);   

本质上,当父母想知道孩子会告诉它的事情时,您在孩子上设置一个委托作为父母,然后在孩子代码中您首先检查该委托是否存在,然后确保它响应您将发送的选择器。 然后你向它发送一条消息。

通过使用@protocol 来实现这一点的好方法

这是一个包含一些基本信息的链接

http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM