gpt4 book ai didi

iOS 子类 UIView - 如何从 ViewController 调用 UIButton 方法?

转载 作者:行者123 更新时间:2023-11-28 22:49:04 26 4
gpt4 key购买 nike

我有一个自定义 UIView,用于显示弹出窗口(在 iPhone 上)。在弹出窗口中有一些 UIButton,我需要从 ViewController 的类(不是 UIView 的类,而是显示 UIView 的 View )调用方法。

如何正确设置它?

位于自定义 UIView 类中的 UIView 按钮代码:

    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoutButton setTitle:@"Logout" forState:UIControlStateNormal];
[logoutButton setFrame:CGRectMake(0, 0, content.frame.size.width, 44)];
[logoutButton addTarget:self.superview.superview action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
[logoutButton setBackgroundImage:redImage forState:UIControlStateNormal];
[logoutButton setBackgroundImage:redImageHighlight forState:UIControlStateHighlighted];
[logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[content addSubview:logoutButton];

最佳答案

执行此操作的最佳方法是在您的 UIView 子类中使用委托(delegate)模式,以便在您的注销按钮被按下时通知所有者。在 View Controller 中创建 View 实例时,将委托(delegate)设置为 self。

http://enroyed.com/ios/delegation-pattern-in-objective-c-and-writing-custom-delegates/ 中查看“编写自定义委托(delegate)”

不能以您在上面的代码中尝试过的方式访问连接到父 View 的 ViewController。

或者,您可以发布通知。例如。发送应执行注销的应用程序范围的消息。查看 NSNotificationCenter 以了解如何执行此操作。

类似于:

[[NSNotificationCenter defaultCenter] postNotificationName:kShouldLogOutNotification object:nil];

编辑:您肯定希望在您的用例中使用委托(delegate)。

关于iOS 子类 UIView - 如何从 ViewController 调用 UIButton 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12411193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com