UIViewController按钮内部的自定义UIView点击刷新UIViewController

问题描述:

我有一个自定义的UIView已被加载到不同的UIViewController。我在自定义UIView中有一个按钮,它在它自己的类中调用一个方法。我想用这种方法刷新,其中嵌入了UIView。目前,我已经尝试将UIViewController导入到初始化它的UIView中,然后调用一个公用方法,该方法已放入UIViewController中。这个方法里面没有任何东西似乎影响它,我甚至试图改变标题,并且不会工作。我知道这个方法会在我的日志中出现。UIViewController按钮内部的自定义UIView点击刷新UIViewController

任何帮助?

+0

请让你的问题更清楚,希望能用代码。它很难理解你想从文本块中得到什么。谢谢! – Jack

+0

如果不是非常大的数量,它将很难发布代码。我基本上想要从另一个角度更新观点。 –

+0

啊哈,我认为在这种情况下你需要的是委托协议,请参阅http://*.com/questions/6168919/how-do-i-set-up-a-simple-delegate-to-communicate-between - 两个 - 视图 - 控制器 – Jack

这是代理模式开始生效的地方。如果我没有误解,请根据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被触发。

希望它有帮助。