我有一个已加载到不同UIViewController
的自定义UIView。我在自定义UIView
中有一个按钮,它在自己的类中调用一个方法。我希望此方法刷新UIViewController
嵌入的UIView
。目前我已尝试将UIViewController
导入UIView初始化它,然后调用我放入的公共方法UIViewController。在这个方法中发生的任何事情似乎都不会影响它,我甚至尝试更改navigation bar
标题,但这不会起作用。我知道这个方法正在被调用,因为它出现在我的日志中。
任何帮助?
答案 0 :(得分:1)
这是授权模式付诸行动的地方。如果我没有误解,你想根据UIViewController
中的某些动作对UIView
执行一些动作(刷新??),而这又是它自己的视图层次结构的一部分。 / p>
让我们说您的自定义视图包含在类CustomView
中。它有一个名为action
的方法,在某些时候被调用。此外,假设您已将CustomView
实例用于某些视图控制器,即MyViewController1
,MyViewController2
等,作为其视图层次结构的一部分。现在,您希望在action
实例触发CustomView
方法时在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
现在,无论何时触发customViewDidPerformAction
方法,您都希望从任何类(如视图控制器的“刷新”目的)调用action
方法。为此,在您的实现文件(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
然后,在实例化delegate
之后,您需要将此类注册为myCustomView
myCustomView
。假设您已在VC的myCustomView
方法中实例化viewDidLoad
。所以方法体类似于:
-(void)viewDidLoad {
////...........other codes
CustomView* cv = [[CustomView alloc] initWithFrame:<# your frame size #>];
cv.delegate = self;
self.myCustomView = cv;
[cv release];
////......other codes
}
然后你还需要创建一个方法,该方法具有与协议声明相同的方法签名,在同一VC的实现(.m)文件中,并在那里修改你的“刷新”代码:
-(void)customViewDidPerformAction:(CustomView*)customView {
///write your refresh code here
}
你们都准备好了。只要MyViewController1
执行action
方法,CustomView
就会执行您的刷新代码。
您可以在任何VC中遵循相同的机制(符合CustomViewDelegate
协议并实现customViewDidPerformAction:
方法),在其视图层次结构中包含CustomView
,以便在{{ {1}}被触发。
希望它有所帮助。