UIViewController按钮内部的自定义UIView点击刷新UIViewController
我有一个自定义的UIView已被加载到不同的UIViewController
。我在自定义UIView
中有一个按钮,它在它自己的类中调用一个方法。我想用这种方法刷新,其中嵌入了UIView
。目前,我已经尝试将UIViewController
导入到初始化它的UIView中,然后调用一个公用方法,该方法已放入UIViewController中。这个方法里面没有任何东西似乎影响它,我甚至试图改变标题,并且不会工作。我知道这个方法会在我的日志中出现。UIViewController按钮内部的自定义UIView点击刷新UIViewController
任何帮助?
这是代理模式开始生效的地方。如果我没有误解,请根据UIView
中的某些操作对UIViewController
执行一些操作(刷新??),这反过来又是其自己的视图层次结构的一部分。
假设您的自定义视图被包装在类CustomView
中。它有一个名为action
的方法,它在某个时候被调用。此外,假设您已将CustomView
实例用于某些视图控制器,即MyViewController1
,MyViewController2
等,作为其视图层次结构的一部分。现在,当您从CustomView
实例触发action
方法时,您希望在VCS中执行一些操作(刷新)。为此,您需要在CustomView
的头文件中声明协议,并且必须将此协议的处理程序(通常称为委托)注册到CustomView
的实例。头文件看起来是这样的:现在
//CustomView.h
//your include headers...
@class CustomView;
@protocol CustomViewDelegate <NSObject>
-(void)customViewDidPerformAction:(CustomView*)customView;
@end
@interface CustomView : UIView {
//......... your ivars
id<CustomViewDelegate> _delegate;
}
//.......your properties
@property(nonatomic,weak) id<CustomViewDelegate> delegate;
-(void)action;
//....other declarations
@end
,你会喜欢被叫做从任何类(像“刷新”的宗旨视图控制器)每当action
方法被触发customViewDidPerformAction
方法。为此,在您的实现文件(CustomView.m),你需要调用customViewDidPerformAction
方法存根,如果有的话,从你的action
方法内部:
//CustomView.m
//.......initializer and other codes
-(void)action {
//other codes
//raise a callback notifying action has been performed
if (self.delegate && [self.delegate respondsToSelector:@selector(customViewDidPerformAction:)]) {
[self.delegate customViewDidPerformAction:self];
}
}
现在,符合CustomViewDelegate
协议可以注册任何类本身作为回调的接收者customViewDidPerformAction:
。例如,可以说,我们的MyViewController1
视图控制器类符合协议。所以头类会是这个样子:
//MyViewController1.h
//include headers
@interface MyViewController1 : UIViewController<CustomViewDelegate>
//........your properties, methods, etc
@property(nonatomic,strong) CustomView* myCustomView;
//......
@end
然后,你需要注册这个类为myCustomView
一个delegate
,实例化后myCustomView
。假设你已经在VC的viewDidLoad
方法中实例化了myCustomView
。所以方法体将类似于:
-(void)viewDidLoad {
////...........other codes
CustomView* cv = [[CustomView alloc] initWithFrame:<# your frame size #>];
cv.delegate = self;
self.myCustomView = cv;
[cv release];
////......other codes
}
那么你还需要为协议声明,实现(.M)内创建具有同样的方法签名的方法相同的VC和正确的文件你“刷新”代码:
-(void)customViewDidPerformAction:(CustomView*)customView {
///write your refresh code here
}
而且你们都已经设定好了。当action
方法由CustomView
执行时,MyViewController1
将执行您的刷新代码。
可以遵循相同的机构(符合CustomViewDelegate
协议和实现customViewDidPerformAction:
方法)从任何VC内,将含有在它的视图层次一个CustomView
,刷新本身每当action
被触发。
希望它有帮助。
请让你的问题更清楚,希望能用代码。它很难理解你想从文本块中得到什么。谢谢! – Jack
如果不是非常大的数量,它将很难发布代码。我基本上想要从另一个角度更新观点。 –
啊哈,我认为在这种情况下你需要的是委托协议,请参阅http://stackoverflow.com/questions/6168919/how-do-i-set-up-a-simple-delegate-to-communicate-between - 两个 - 视图 - 控制器 – Jack