我从代码中显示图像是代码
UIImageView *preArrowImage =[[UIImageView alloc]init ];
preArrowImage.image =[UIImage imageNamed:@"arrowprev.png"];
preArrowImage.frame = CGRectMake(20, 60, 10, 30);
[self.view addSubview:preArrowImage];
我想以编程方式处理preArrowImage上的触摸事件。
答案 0 :(得分:225)
Objective-c
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
[preArrowImage setUserInteractionEnabled:YES];
[preArrowImage addGestureRecognizer:singleTap];
-(void)tapDetected{
NSLog(@"single Tap on imageview");
}
SWIFT 4.2
let preArrowImage : UIImageView // also give it frame
let singleTap = UITapGestureRecognizer(target: self, action: #selector(tapDetected))
preArrowImage.isUserInteractionEnabled = true
preArrowImage.addGestureRecognizer(singleTap)
//Action
@objc func tapDetected() {
print("Imageview Clicked")
}
答案 1 :(得分:17)
只需在图片上添加UITapGesture
,但请记住启用 UserInteraction 。
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(singleTapGestureCaptured:)];
[preArrowImage addGestureRecognizer:singleTap];
[preArrowImage setMultipleTouchEnabled:YES];
[preArrowImage setUserInteractionEnabled:YES];
答案 2 :(得分:4)
现在在Swift!
let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapDetected"))
singleTap.numberOfTapsRequired = 1
preArrowImage.userInteractionEnabled = true
preArrowImage.addGestureRecognizer(singleTap)
//Action
func tapDetected() {
println("Single Tap on imageview")
}
答案 3 :(得分:4)
Swift 3
在 UIImageView上启用UserInterAction
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if let touch = touches.first {
if touch.view == self.imgVwPostPreview { //image View property
//Do your actions
//self.delegate?.didClickOnCellImageView(indexPath: self.cellIndexPath!)
}
}
}
答案 4 :(得分:3)
在视图控制器中使用带有视图的故事板。
选择其中一个手势识别器后,将其拖动到控制器。
现在它将显示在&#34;文档大纲&#34;和视图控制器xib的标题。
将手势拖动到UILable
在头文件中创建IBAction方法
现在将它从处理程序拖到xib中的手势图标
答案 5 :(得分:0)
如果你的UIImageView是一个从Storyboard或Nib获得的IBOutlet,你可以在图像视图中添加一个UIGestureRecognizer,启用用户交互并将IBAction连接到手势识别器。
有关详情,请查看我对此问题的回答:How to you make a UIImageView on the storyboard clickable (swift)
答案 6 :(得分:0)
这是另一种选择:作弊。
我的意思是,横向思考。
按照你想要的方式设置你的UIImage,裁剪,方面适合等等。
用UIView(等尺寸,位置等)覆盖它
将背景设置为clearcolour,将类设置为UIControl。
将事件内部的触摸指向处理程序,瞧。
答案 7 :(得分:0)
Xamarin.iOS
UIImageView preArrowImage; // also give it frame
var singleTap = new UITapGestureRecognizer(TapDetected);
singleTap.ShouldReceiveTouch -= TapGesture_ShouldReceiveTouch;
singleTap.ShouldReceiveTouch += TapGesture_ShouldReceiveTouch;
preArrowImage.UserInteractionEnabled = true;
preArrowImage.AddGestureRecognizer(singleTap)
bool TapGesture_ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch)
{
return true;
}
void TapDetected(UITapGestureRecognizer tapGestureRecognizer)
{
print("Imageview Clicked")
}