ios - 在目标 View Controller 上设置委托(delegate)

标签 ios objective-c uitextfielddelegate

这让我很困惑。
上下文
The original tutorial I'm following.
enter image description here
通过自定义 segue 将 segue 添加到主视图的位置:

- (void) perform {
    
    MainViewController *source = (MainViewController *)self.sourceViewController;
    UIViewController *destination = (UIViewController *) self.destinationViewController;
    
    for(UIView *view in source.main.subviews){
        [view removeFromSuperview];
    }
    
    source.currentViewController = destination;
    destination.view.frame = CGRectMake(0, 0, source.main.frame.size.width, source.main.frame.size.height);
    [source.main addSubview:destination.view];
}
文本字段 在 subview Controller 中作为委托(delegate)连接。在所有条件相同的情况下,我让应用程序崩溃而没有任何消息。

解决方法
在主视图 Controller 中,-(void)prepareForSegue:我已添加 [segue.destinationViewController setDelegate:self];同时我在 subview Controller 中添加了一个属性 id<UITextFieldDelegate> delegate并将文本字段委托(delegate)修改为 self.delegate .
这可行,但问题是我必须在主视图 Controller 中设置委托(delegate)方法,这不是很有效,因为我有更多的 View Controller 要添加。

目标
如何将每个 View Controller 设置为自身的委托(delegate)而不崩溃?

最佳答案

您的错误的直接原因是您的 View 所属的 View Controller 正在被释放。当 View Controller 被解除分配时,您的 View 在屏幕上这一事实突出了将 View 从一个 View Controller 中取出并将它们添加到另一个 View Controller 的方法中的一个根本缺陷。 View Controller 包含是解决此类问题的正确方法。

将 currentViewController 属性更改为 strong 将解决您看到的内存管理问题,但这只是一个创可贴。您的 currentViewController 仍将缺少旋转方法、外观和消失方法、布局方法等。 View Controller 包含确保为 View 在屏幕上的 View Controller 调用这些方法。

Here is an altered version of your project这说明了如何使用 View Controller 包含。我认为这将是一个比手动删除和添加 View Controller 本身的 subview 更好的解决方案。见 the Apple docs有关自定义 View Controller 容器的更多信息。

关于ios - 在目标 View Controller 上设置委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26051057/

相关文章:

ios - 如何在 iOS 上的 Swift 中以编程方式获取 UDID

ios - 将按钮和文本添加到 UITableView 中的节页脚

ios - 表达式解析为未使用的函数 (Swift)

Swift 如何在所有 uiTextfield 上退出第一响应者

swift - 有什么方法可以使 UITextFieldDelegate 在 swift 中更具动态性?

iphone - 选择器只会显示 3 个对象

objective-c - 需要有关消耗 RAM 的循环的帮助

objective-c - 使用键盘的 "Return"(完成)按钮调用方法

objective-c - 如何为 dataWithContentsOfURL :url 设置超时

ios - 需要在 Swift 中的 UITextField 委托(delegate)方法中引用自定义 UITableViewCell,而不使用标签属性