我一直在試圖做這個簡單的事情:添加一個動作到一個簡單的自定義視圖。我期待在互聯網上,發現了兩個「易」解決方案:添加動作到自定義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