我有一个分页UIScrollView
,每个页面只有一个UIImageView
和一个View。我想添加对视图上显示的图像的描述,我希望能够通过点击UIImageView
来显示/隐藏视图。
我尝试了几种添加GestureRecognizer
的方法,但是似乎不起作用。下面的代码是创建我的页面的地方。幻灯片1和幻灯片2显示了2种不同的方式,我尝试添加GestureRecognizer
。
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
@objc func showOrHide(){
print("tapped")
for slide in slides{
slide.labelView.isHidden = true
}
}
func createSlides() -> [Slide] {
print("creating Slides")
let slide1:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
slide1.imageView.image = UIImage(named: "img1.jpg")
slide1.imageView.isUserInteractionEnabled = true
slide1.tapGestureRecogizer = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
let slide2:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
slide2.imageView.image = UIImage(named: "img2.jpg")
slide2.imageView.isUserInteractionEnabled = true
slide2.imageView.addGestureRecognizer(tapGesture)
我认为我对这些页面的创建方式有误解,希望有人能帮助我。
谢谢!
答案 0 :(得分:1)
tapGesture
中将createSlides
创建为局部变量。 更新的代码:
func createSlides() -> [Slide] {
print("creating Slides")
let slide1 = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
slide1.imageView.image = UIImage(named: "img1.jpg")
slide1.imageView.isUserInteractionEnabled = true
var tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
slide1.imageView.addGestureRecognizer(tapGesture)
let slide2 = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
slide2.imageView.image = UIImage(named: "img2.jpg")
slide2.imageView.isUserInteractionEnabled = true
tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
slide2.imageView.addGestureRecognizer(tapGesture)