我有图像滑块..我按照本教程进行操作:Create a Horizontal Paging UIScrollView with UIPageControl Swift 4 XCode 9,它工作正常。.
现在我想在这些图像上添加手势识别器..我试图这样做:
func createSlides() -> [banner] {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide1.img.image = UIImage(named: "bannerex")
slide1.img.addGestureRecognizer(tapGesture)
let slide2:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide2.img.image = UIImage(named: "bannerex")
slide2.img.addGestureRecognizer(tapGesture)
let slide3:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide3.img.image = UIImage(named: "bannerex")
slide3.img.addGestureRecognizer(tapGesture)
return [slide1, slide2, slide3]
}
@objc func tapped(_ sender: UITapGestureRecognizer){
print("tapped")
print(pageControl.currentPage)
}
但是它不起作用,什么也不会发生。
如何解决此问题?
import UIKit
class banner: UIView {
@IBOutlet weak var img: UIImageView!
}
答案 0 :(得分:3)
这里有两个问题:
isUserInteractionEnabled
默认为false
我建议不要将该代码放在isUserInteractionEnabled
类本身中,而不是分别为每个图像视图将true
设置为Banner
。由于您似乎是从情节提要中初始化的,因此使用awakeFromNib
函数应该可以正常工作:
class Banner: UIView {
@IBOutlet weak var img: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
img.isUserInteractionEnabled = true
}
}
在您的createSlides()
函数中,向每个视图添加单独的点击手势:
let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide1.img.image = UIImage(named: "bannerex")
slide1.img.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))
甚至对于扩展和无代码冗余都更好:
function tap() -> UITapGestureRecognizer {
return UITapGestureRecognizer(target: self, action: #selector(tapped))
}
let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide1.img.image = UIImage(named: "bannerex")
slide1.img.addGestureRecognizer(tap())
答案 1 :(得分:2)
UITapGestureRecognizer
仅可用于单个视图,因此,如果要检测每个UITapGestureRecognizer
上的敲击,则需要为每个图像创建不同的image
。了解更多HERE。
并且您需要将每个isUserInteractionEnabled
的{{1}}设置为true
。
答案 2 :(得分:0)
Image views默认情况下忽略用户事件。如果希望图像视图也处理用户交互,请将其isUserInteractionEnabled
属性的值更改为true。