【发布时间】:2017-02-08 17:29:17
【问题描述】:
我在将UITapGestureRecogniser 用于tableViewCell 中的图像时遇到问题。我在tableViewCell 中创建了对象UIImageView 的出口,我的要求是每当我点击imageView 时,必须显示其他图像。我试过下面的代码,但没有成功。
任何帮助将不胜感激!
单元格
import UIKit
class resultsTableViewCell: UITableViewCell {
@IBOutlet weak var star_selected: UIImageView!
@IBOutlet weak var star_unselected: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
视图控制器
class resultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
@IBOutlet weak var resultsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
flightCodeView = FlightCodeView(frame: CGRect.zero)
self.view.addSubview(flightCodeView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultsCellIdentifier", for: indexPath) as! resultsTableViewCell
let image : UIImage = UIImage(named: "star_unselected")!
cell.star_unselected.image = image
let tapGesture = UITapGestureRecognizer(target: self, action: Selector(("ImageSelected")))
cell.star_unselected.addGestureRecognizer(tapGesture)
tapGesture.delegate = self
return cell
}
func ImageSelected(sender: UITapGestureRecognizer? = nil) {
// just creating an alert to prove our tap worked!
let image: UIImage = UIImage(named: "star_selected.png")!
cell.star_selected.image = image
}
}
【问题讨论】:
-
在单元类外部调用这个函数,func ImageSelected(sender: UITapGestureRecognizer? = nil) { print("yess") // 只是创建一个警报来证明我们的点击有效!让图像:UIImage = UIImage(命名:“star_selected.png”)! cell.star_selected.image = 图片 }
-
默认情况下,UIImageView不会为 userInteraction 启用,因此请务必在 StoryBoard 或代码中进行设置
-
在您的方法 awakeFromNib 中从您的单元格中添加
isUserInteractionEnabled = true。添加你的手势也在那里识别。 -
顺便说一句,Swift 约定以小写字母开头的类命名