从其视图触发 UIViewController 中的方法 [英] Trigger a method in UIViewController from its View
本文介绍了从其视图触发 UIViewController 中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 UIViewController
,它的 UIView
包含一个 UIButton
.我想在按钮点击事件上触发 UIViewController
中的一个方法.
保持对 UIViewController
的引用似乎不是一个好主意,如以下链接所述:从 UIView 到 UIViewController?
I have a UIViewController
with its UIView
which contains a UIButton
. I want to trigger a method in UIViewController
on button click event.
Keeping reference of UIViewController
doesn't seem to be a good idea like the following link says:
Get to UIViewController from UIView?
所以我想使用委托来实现这一点.关于如何实现这一目标的任何提示?
So I want to achive this using a delegate. Any hint on how to achieve this?
推荐答案
你可以这样做
CustomView.h
#import <UIKit/UIKit.h>
@protocol CustomViewDelegate <NSObject>
-(void)didButtonPressed;
@end
@interface CustomView : UIView
@property (assign) id<CustomViewDelegate> delegate;
@end
CustomView.m
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor whiteColor];
//[self addSubview:titleLbl];
UIButton *button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 50);
[button addTarget:self.delegate action:@selector(didButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"pressMe" forState:UIControlStateNormal];
[self addSubview:button];
}
return self;
}
在你的 ViewController.m
-(void)loadView
{
[super loadView];
CustomView *view = [[CustomView alloc]initWithFrame:self.view.bounds];
view.delegate = self;
[self.view addSubview:view];
}
这篇关于从其视图触发 UIViewController 中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文