我创建了一个带故事板的自定义UIViewController,这是类: .h文件:
#import <UIKit/UIKit.h>
@interface PlayerViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *PlayerNumber;
@property (weak, nonatomic) IBOutlet UIImageView *PlayerImage;
@property (weak, nonatomic) IBOutlet UILabel *PlayerNameLabel;
-(void)setPlayerName:(NSString*)PlayerNameString;
@end
.m文件:
#import "PlayerViewController.h"
@interface PlayerViewController ()
@end
@implementation PlayerViewController
@synthesize PlayerImage,PlayerNameLabel,PlayerNumber;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)setPlayerName:(NSString *)PlayerNameString{
self.PlayerNameLabel.text=PlayerNameString;
}
@end
从主视图我创建了2个PlayerViewController实例,以显示2个自定义视图:
- (void)viewDidLoad {
[super viewDidLoad];
[self DrawPlayerWithTag:1];
[self DrawPlayerWithTag:2];
}
- (void)DrawPlayerWithTag:(int)PlayerTag{
PlayerViewController *myPlayerViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PlayerViewController"];
UIView *myPlayerView=myPlayerViewController.view;
myPlayerView.tag=PlayerTag;
myPlayerView.frame=CGRectMake(0, 0, 100, 100);
myPlayerView.center = CGPointMake(self.view.frame.size.width / 2,
self.view.frame.size.height / 2);
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doDoubleTap)];
doubleTap.numberOfTapsRequired = 2;
[myPlayerView addGestureRecognizer:doubleTap];
[self.view addSubview:myPlayerView];
[myPlayerViewController setPlayerName:@"NameA"];
}
似乎有效。 但是,如果我想更改PlayerName,在双击事件后如何引用view1而不是view2,并使用方法setPlayerName?
非常感谢您的回答!
答案 0 :(得分:0)
更改回调方法
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doDoubleTap:)];
您可以像这样获取视图的标记:
-(void)doDoubleTap:(UITapGestureRecognizer *)gesture{
NSLog(@"%ld", gesture.view.tag);
}
您可以保留代码并使用此帖Get to UIViewController from UIView?
调用setPlayerName
但是,我建议这样:
gesture
的目标设定为myPlayerViewController
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:myPlayerViewController action:@selector(doDoubleTap:)];
在&#34;主视图&#34;中保留myPlayerViewController的引用通过如下数组:
[arrPlayerView addObject:myPlayerViewController]; /// keep pointing to myPlayerViewController, so it isn't released.
将(void)doDoubleTap:(UITapGestureRecognizer *)gesture
放入PlayerViewController