gpt4 book ai didi

ios - 从 UIButton 的类中获取当前的 UIViewController

转载 作者:行者123 更新时间:2023-11-29 02:45:50 25 4
gpt4 key购买 nike

我有自定义 UIButton,它通过协议(protocol)以编程方式与 ViewController 方法交互(触发)。但是按钮的行为必须依赖于放置的 ViewController。我这样做是为了尽量减少 ViewControllers 本身的代码量,因为按钮必须保持不变并具有相同的功能(导航)。UIButton 的自定义类中有没有什么方法可以获取它所在的 ViewController?

最佳答案

我会以特定方式遵循@rmaddy 的建议,借鉴 SDK 的风格

// MyCutomButton.h
@protocol MyCustomButtonDatasource;

@interface MyCustomButton : UIButton
@property(weak,nonatomic) IBOutlet id<MyCustomButtonDatasource>datasource;
// etc
@end

@protocol MyCustomButtonDatasource <NSObject>
@optional
- (NSString *)howShouldIBehave:(MyCustomButton *)button;
@end

现在按钮可以在 IB 中设置它的数据源。包含它的 View Controller 将需要一些额外的代码(抱歉,在好的设计中这是不可避免的)。他们将声明自己实现了 MyCustomButtonDatasource。

当 MyCustomButton 需要根据其放置位置有条件地运行时,它可以询问其数据源...

// MyCustomButton.m

NSString *string = @"defaultBehavior"; // per @RichardTopchiy's suggestion
if ([self.datasource respondsToSelector:@selector(howShouldIBehave:)])
string = [self.datasource howShouldIBehave:self];

// string is just made-up here, have it answer something simple (int, BOOL)
// that lets the button proceed with the right behavior. Don't ask for
// anything that relies on specific knowledge of how MyCustomButton
// is implemented

编辑 - 要创建关系,如果您已将属性装饰为 IBOutlet(如上所示),您应该能够在 IB 中设置关系。将您的 View Controller 声明为实现 <MyCustomButtonDatasource> .选择您的自定义按钮,然后选择连接检查器,然后拖动到您的 View Controller 。

或者,使按钮本身成为 View Controller 中的 IBOutlet 属性,并在 viewDidLoad 中执行:

self.customButton.datasource = self;

最后一种方法是给你的按钮一个标签,比如 128,然后:

MyCustomButton *customButton = (MyCustomButton *)[self.view viewWithTag:128];
self.customButton.datasource = self;

关于ios - 从 UIButton 的类中获取当前的 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25145178/

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