我正在创建 UILabel 的多个实例以显示在具有许多标签的地图上,并允许用户返回所选标签的 ID 或标签号。下面的代码只返回最后创建的实例,可能是由于相同的变量“newCity”。
这两个实例将具有从 pList 动态填充的数据,我将遍历该 pList 以获取标签的城市、idNumber 和 x & y 位置。每次城市的数量都会不同,甚至可能会动态变化。为了清楚起见,显示了两个。
问题是如何为被点击的正确标签获取正确的 idNumber?我搜索了很多地方,但没有找到可以在不引起其他问题的情况下工作的解决方案。如何创建新实例并仍然获得正确的实例?
还要注意下面的 tapGestureRecognizer 有 tapGesture 和 tapGesture2 名称。它不适用于同一个。如何使用带有一个名称的 tapGesture 并识别哪个标签?
除非没有其他方法,否则我宁愿使用标签而不是按钮。我什至可以添加一个 touchesBegan 或 touchesMoved 来调整我不想与标签中的 tapGesture 冲突的子视图。
我感谢您的帮助。
WBCitiesView.h
@interface WBCitiesView : UIViewController
{
UIView *subView;
int resultNumber;
}
@property(nonatomic, strong) UIView *subView;
@property int resultNumber;
- (void) touchUp:(id)sender;
@end
WBCitiesView.m
#import "WBCitiesView.h"
#import "WBCities.h"
@interface WBCitiesView ()
@end
@implementation WBCitiesView
@synthesize subView, resultNumber;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
WBCities *newCity;
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect mapFrame = CGRectMake(20, 30, 250, 300);
subView = [[UIView alloc]initWithFrame:mapFrame];
subView.backgroundColor = [UIColor grayColor];
subView.alpha = .5;
subView.autoresizesSubviews=YES;
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:subView action:@selector(swipe:)];///was self
[subView addGestureRecognizer:swipe];
[self.view addSubview:subView];
newCity =[[WBCities alloc] initWithFrame:CGRectMake(50, 20, 100, 30)];
newCity.city = @"CityA";
newCity.idNumber = 1111;
newCity.size = 0;
[newCity setBackgroundColor:[UIColor blueColor]];
[newCity setText:newCity.city];
[newCity setTag:newCity.idNumber];
newCity.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchUp:)];
[newCity addGestureRecognizer:tapGesture];
[subView addSubview:newCity];
newCity =[[WBCities alloc] initWithFrame:CGRectMake(100, 70, 100, 30)];
newCity.city = @"CityB";
newCity.idNumber = 2222;
newCity.size = 1;
[newCity setBackgroundColor:[UIColor yellowColor]];
[newCity setText:newCity.city];
[newCity setTag:newCity.idNumber];
newCity.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchUp:)];
[newCity addGestureRecognizer:tapGesture2];
[subView addSubview:newCity];
-(void) touchUp:(id)sender
{
resultNumber = [newCity returnIdNumber];
}
WBCities.h
@interface WBCities : UILabel{
NSString *city;
int idNumber;
BOOL size;
}
@property (nonatomic, strong) NSString *city;
@property (nonatomic) int idNumber;
@property (nonatomic) BOOL size;
-(int)returnIdNumber;
@end
WBCities.m
#import "WBCities.h"
#import "WBCitiesView.h"
@implementation WBCities
@synthesize city, idNumber, size;
-(id)init{
self = [super init];
if (self){
}
return self;
}
-(int)returnIdNumber{
return idNumber;
}
@end