按钮操作和轻击手势在UIView XIB上不起作用

问题描述 投票:0回答:1

我在XIB中添加了自定义UIView。我只是尝试执行按钮操作和手势,即使对包括ContentView在内的所有元素都启用了用户交互,也无济于事。

初始化UIView

-(void)initializeSubviews {
    self.backgroundColor = [UIColor clearColor];

    [[[NSBundle mainBundle]loadNibNamed:@"DatesView" owner:self options:nil]firstObject];
    [self addSubview:self.contentView];

   // self.contentView.frame = self.bounds;

    [self.fromDateButton addTarget:self action:@selector(tapOnfromDate:) forControlEvents:UIControlEventTouchUpInside];
    self.fromDateButton.backgroundColor = [UIColor redColor];


}

点击手势

UITapGestureRecognizer *fromDateTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnfromDate)];
    [datesView.contentView addGestureRecognizer:fromDateTapRecognizer];
    [datesView.fromMonthYearLabel addGestureRecognizer:fromDateTapRecognizer];
    [datesView.fromDayLabel addGestureRecognizer:fromDateTapRecognizer];

按钮动作

[datesView.fromDateButton addTarget:self action:@selector(tapOnfromDate) forControlEvents:UIControlEventTouchUpInside];

UIView界面

enter image description here

ios swift uiview uibutton xib
1个回答
0
投票

耦合事物...

1)通过在您的视图子类中注释此行:

// self.contentView.frame = self.bounds;

视图以0,0框结束。按钮和标签等可见,因为视图默认为.clipsToBounds = NO,但对象不接受用户交互。

2] UITapGestureRecognizer是单个实例。如果将其添加到一个视图中,然后尝试将其添加到其他视图中,它将仅存在于添加了该视图的最后一个视图上。

尝试这样(请确保取消注释上面的行):

- (void)viewDidLoad {
    [super viewDidLoad];

    // do all the loading stuff here...

    // local declaration
    UITapGestureRecognizer *tapRecognizer;

    // Optional --- make *sure* user interaction is enabled
    [datesView.contentView setUserInteractionEnabled:YES];
    [datesView.fromMonthYearLabel setUserInteractionEnabled:YES];
    [datesView.fromDayLabel setUserInteractionEnabled:YES];

    // new recognizer
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnfromDate:)];
    // add it to contentView
    [datesView.contentView addGestureRecognizer:tapRecognizer];

    // new recognizer
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnfromDate:)];
    // add it to fromMonthYearLabel
    [datesView.fromMonthYearLabel addGestureRecognizer:tapRecognizer];

    // new recognizer
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnfromDate:)];
    // add it to fromDayLabel
    [datesView.fromDayLabel addGestureRecognizer:tapRecognizer];

    // add target action to fromDateButton
    [datesView.fromDateButton addTarget:self action:@selector(fromDateButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

}

- (void) tapOnfromDate: (UITapGestureRecognizer *)recognizer {
    NSLog(@"Tapped! %@", recognizer.view);
}

- (void) fromDateButtonTapped: (id)sender {
    NSLog(@"Button Tapped! %@", sender);
}
© www.soinside.com 2019 - 2024. All rights reserved.