[英]How to set subview as a first responder?
我試圖在單擊關閉按鈕時關閉圖像視圖。但是按鈕不響應觸摸事件。 這是我的代碼:
-(void)imageTouchUP:(id)sender
{
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectInset(self.view.bounds, 30 , 30)];
imageView.image=self.testimonialImage;
imageView.tag=1;
UIButton *closeButton=[UIButton buttonWithType:UIButtonTypeCustom];
closeButton.frame=CGRectMake(0, 0, 20, 20);
[closeButton setImage:[UIImage imageNamed:@"close.jpg"] forState:UIControlStateNormal];
[closeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:closeButton];
[self.view addSubview:imageView];
}
-(void)buttonClicked:(id)sender
{
UIView *subView=[self.view viewWithTag:1];
[subView removeFromSuperview];
}
為了使UIImageView處理觸摸,您需要將userInteractionEnabled設置為YES,它默認為NO。 嘗試:
[imageView setUserInteractionEnabled:YES];
UIImageView userInteractionEnabled
有1個屬性,其值默認為NO。 所以在你的代碼中添加
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectInset(self.view.bounds, 30 , 30)];
imageView.userInteractionEnabled = YES;
也許在您的self.view中還有另一個帶有tag = 1的視圖。 請嘗試編輯這樣單擊的按鈕:
- (void) buttonClicked:(UIButton *)btn
{
UIView *view = btn.superview;
if ([view isKindOfClass:[UIImageView class]]) {
[view removeFromSuperview];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.