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

标签 ios objective-c uiviewcontroller uibutton

我有自定义 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/

相关文章:

ios - 仅可见 View 动画

objective-c - 如何将原始字节写入 NSMutableData 对象?

objective-c - 将 CIImage 转换为 NSImage

iphone - 从 Non-Storyboard ViewController 转到 ViewController

ios - segue完成后如何执行一些代码?

ios - UIButton高亮显示的图像未显示

ios - 在 Swift 中测试和加载高分

objective-c - 从 UIButton 中获取 UILabel

ios - 播放本地视频文件

ios - 如何通过核心数据代码进行过滤