在UIViewController按钮内自定义UIView单击以刷新UIViewController

时间:2014-02-12 22:34:09

标签: ios objective-c uiview uiviewcontroller

我有一个已加载到不同UIViewController的自定义UIView。我在自定义UIView中有一个按钮,它在自己的类中调用一个方法。我希望此方法刷新UIViewController嵌入的UIView。目前我已尝试将UIViewController导入UIView初始化它,然后调用我放入的公共方法UIViewController。在这个方法中发生的任何事情似乎都不会影响它,我甚至尝试更改navigation bar标题,但这不会起作用。我知道这个方法正在被调用,因为它出现在我的日志中。

任何帮助?

1 个答案:

答案 0 :(得分:1)

这是授权模式付诸行动的地方。如果我没有误解,你想根据UIViewController中的某些动作对UIView执行一些动作(刷新??),而这又是它自己的视图层次结构的一部分。 / p>

让我们说您的自定义视图包含在类CustomView中。它有一个名为action的方法,在某些时候被调用。此外,假设您已将CustomView实例用于某些视图控制器,即MyViewController1MyViewController2等,作为其视图层次结构的一部分。现在,您希望在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}}被触发。

希望它有所帮助。