问题描述
我有自定义 UIButton,它通过协议以编程方式与 ViewController 方法交互(触发器).但是按钮的行为必须依赖于放置的 ViewController.我这样做是为了最大限度地减少 ViewControllers 本身的代码量,因为按钮必须保持不变并具有相同的功能(导航).UIButton 的自定义类中是否有任何方法可以获取它所在的 ViewController?
I have custom UIButton which programmatically interacts (triggers) with ViewController methods via protocol. But the behaviour of the button has to be dependent on the ViewController placed on. I do this to minimise amount of code in ViewControllers itself, as the button has to remain the same and bear the same functions (navigation).Is there any way in UIButton's custom class to get the ViewController it is placed on?
推荐答案
我会以特定的方式遵循@rmaddy 的建议,借鉴 SDK 的风格
I'd follow @rmaddy advice in a specific way, borrowing from the SDK's style
// 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 中设置它的数据源.包含它的视图控制器需要一些额外的代码(抱歉,在好的设计中这是不可避免的).他们将声明自己实现了 MyCustomButtonDatasource.
Now the button can have it's datasource set in IB. View controllers that include it will need a little additional code (sorry, it's unavoidable in a good design). They will declare themselves as implementing MyCustomButtonDatasource.
当 MyCustomButton 需要根据它的放置位置有条件地表现时,它可以询问其数据源...
When MyCustomButton needs to behave conditionally based on where it's placed, it can ask its datasource...
// 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
EDIT - 要创建关系,如果您将属性装饰为 IBOutlet(如上所示),您应该能够在 IB 中设置关系.将您的视图控制器声明为实现 .选择您的自定义按钮,然后选择连接检查器,然后拖动到您的视图控制器.
EDIT - To create the relationship, if you've decorated the property as an IBOutlet (as shown above), you should be able to setup the relationship in IB. Declare your view controller as implementing <MyCustomButtonDatasource>
. Select your custom button, then the connections inspector, then drag to your view controller.
或者,使按钮本身成为视图控制器中的 IBOutlet 属性,并在 viewDidLoad 中执行:
Alternatively, make the button itself an IBOutlet property in the view controller and, in viewDidLoad, do:
self.customButton.datasource = self;
最后一种方法是给你的按钮一个标签,比如 128,然后:
The last way to do it is give your button a tag, say, 128, then:
MyCustomButton *customButton = (MyCustomButton *)[self.view viewWithTag:128];
self.customButton.datasource = self;
这篇关于从 UIButton 的类中获取当前的 UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!