我一直在试图做这个简单的事情:添加一个动作到一个简单的自定义视图。我期待在互联网上,发现了两个“易”解决方案:添加动作到自定义uiview
UITapGestureRecognizer
UIButton
我想以编程方式做到这一点,我只需要处理自来水。
这是我的代码到目前为止,我已经尝试了两种解决方案单独和一起,它不工作!
.M
#import "AreaView.h"
@implementation AreaView
#define GREY 27.0/255.0
#define PINK_R 252.0/255.0
#define PINK_G 47.0/255.0
#define PINK_B 99.0/255.0
- (id) initWithFrame:(CGRect)frame imageName:(NSString *)imageName areaName:(NSString *)areaName minimumSpending:(int)minimumSpending andCapacity:(int)capacity
{
self = [self initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithRed:GREY green:GREY blue:GREY alpha:1];
self.userInteractionEnabled=YES;
//Init variables
_areaName=areaName;
_capacity=capacity;
_minimumSpending=minimumSpending;
//Image view
_logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 4, 66, 50)];
//_logoImageView.image = [UIImage imageNamed:imageName];
_logoImageView.backgroundColor = [UIColor grayColor];
//Label
_areaNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 54, 76, 18)];
_areaNameLabel.textAlignment = NSTextAlignmentCenter;
_areaNameLabel.textColor = [UIColor whiteColor];
_areaNameLabel.font = [UIFont systemFontOfSize:12.0];
_areaNameLabel.text = areaName;
//button
_button = [[UIButton alloc]initWithFrame:self.bounds];
_button.userInteractionEnabled=YES;
_button.backgroundColor=[UIColor yellowColor];
[_button addTarget:self action:@selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];
//tap gesture racognizer
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setDelegate:self];
[self addGestureRecognizer:tapRecognizer];
[self addSubview:_logoImageView];
[self addSubview:_areaNameLabel];
[self addSubview:_button];
}
return self;
}
-(void)handleTap:(UIButton *)button
{
NSLog(@"tapped!");
}
-(void)tapped:(UITapGestureRecognizer *)recognizer
{
NSLog(@"tapped!");
}
@end
.H
#import <UIKit/UIKit.h>
@interface AreaView : UIView <UIGestureRecognizerDelegate>
@property (nonatomic) UIImageView *logoImageView;
@property (nonatomic) UILabel *areaNameLabel;
@property (nonatomic) NSString *areaName;
@property (nonatomic) int minimumSpending;
@property (nonatomic) int capacity;
- (id) initWithFrame:(CGRect)frame imageName:(NSString *)imageName areaName:(NSString *)areaName minimumSpending:(int)minimumSpending andCapacity:(int)capacity;
@property (nonatomic, strong) UIButton *button;
@end
感谢您的帮助!
编辑
的问题是,handleTap和挖掘都从未被触发,即使我的评论按钮溶液或点击手势一个单独测试。对于按钮实现,我可以在我的界面上看到它,但点击它却什么都不做。
我的UIView然后在UIScrollview中以编程方式多次添加(对于多个视图)。
编辑2
的问题是比这更复杂化。自定义视图位于scrollview内部,该视图位于另一个不同的自定义视图内,其主要功能是重写hittest,因此该视图的触摸由scrollview保存。 (Here is the purpose of all that)。
似乎只要涉及触击测试,它就不起作用。
你是什么意思'它不工作'?按钮动作是否被触发? – Mani
你卡在哪里? –
因为我认为这应该至少有一个事件。重新检查您的代码。 – Chathurka