![](/img/trans.png)
[英]How to add UIViewController as target of UIButton action created in programmatically created UIView?
[英]Add target for UIView Programmatically
在我看來,我想添加一個目標,當我點擊視圖時應該觸發該目標。 我可以通過IB做同樣的事情,或者我甚至在代碼中為按鈕做了這件事。 但是我不知道如何以編程方式為UIView做這件事。
任何人之前都這樣做過。
幫我。
要單擊UIView
您必須使用UIGestureRecognizer
或UITouch
。 這只會有助於提示行動。 UIButton
有一個選擇器方法,而UIView沒有任何這樣的方法。 此外, UIImageViews
等也是如此。
您可以使用UIGestureRecognizer
此目的。
第1步:
將您的UIView
添加為viewcontroller中的屬性
@property (strong, nonatomic) IBOutlet UIView *yourView;
第2步:
為您的UIView設置UIGestureRecognizer
。
- (void)viewDidLoad {
[super viewDidLoad];
UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[self.yourView addGestureRecognizer:gesture];
}
第3步:
處理UIView上的點擊。
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
//to get the clicked location inside the view do this.
CGPoint point = [gestureRecognizer locationInView:self.yourView];
}
請記住,A UIGestureRecognizer將與單個視圖一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.