Использование параметров в действии UITapGestureRecognizer в Swift
Я пытаюсь вызвать функцию с параметрами, используя действие UITapGestureRecognizer
, и я не могу найти альтернативы.
Это жест, который, как предполагается, вызывает функцию doubleTap с параметром indexPath
.
var gestureDoubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTap(indexPath)")
Это функция, которая должна быть вызвана.
func doubleTap(indexPath: NSIndexPath) {
NSLog("double tap")
NSLog("%@", indexPath.row)
}
Как я могу вызвать функцию doubleTap
с параметром indexPath
?
Спасибо за все предложения.
EDIT - это весь мой код, он в основном настраивает имя объекта, так что мой второй viewController может его получить и использовать
import UIKit
class viewController1: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var imageArray:[String] = []
var name : AnyObject? {
get {
return NSUserDefaults.standardUserDefaults().objectForKey("name")
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue!, forKey: "name")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as myViewCell
//adding single and double tap gestures for each cell
/////////////////////////////
//ISSUE IS SENDING indexPath TO doubleTap FUNC
var gestureDoubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTap:")
gestureDoubleTap.numberOfTapsRequired = 2
cell.addGestureRecognizer(gestureDoubleTap)
var gestureSingleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTap")
gestureSingleTap.numberOfTapsRequired = 1
cell.addGestureRecognizer(gestureSingleTap)
cell.imgView.image=UIImage(named: imageArray[indexPath.row])
return cell
}
//func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
//
// name = imageArray[indexPath.row]
//}
override func viewDidLoad(){
super.viewDidLoad()
imageArray=["1.png","2.png","2.png","1.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png"]
}
func doubleTap(sender: UITapGestureRecognizer) {
var tapLocation = sender.locationInView(self.collectionView)
var indexPath:NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!
//var cell = self.collectionView.cellForItemAtIndexPath(indexPath)
NSLog("double tap")
NSLog("%@", indexPath)
//NSLog("%@", cell!)
//THIS IS THE GOAL----- set 'name' with the appropriate img corresponding the cell
//name = imageArray[indexPath]
//self.performSegueWithIdentifier("segue", sender: nil)
}
func singleTap() {
NSLog("single tap")
}
}
Ответы
Ответ 1
Учитывая, что у вас есть NSIndexPath
, я полагаю, вы хотели бы получить соответствующий indexPath
из точки касания касания на UITableView
.
UIGestureRecognizer
имеет один (или нет) параметр. Когда есть один, он проходит сам - indexPath
, однако, не передается функции, как указано.
Скажем, мы имеем следующее:
let aTap = UITapGestureRecognizer(target: self, action: "tapped:")
и соответствующей функции при нажатии на просмотр:
func tapped(sender: UITapGestureRecognizer)
{
//using sender, we can get the point in respect to the table view
let tapLocation = sender.locationInView(self.tableView)
//using the tapLocation, we retrieve the corresponding indexPath
let indexPath = self.tableView.indexPathForRowAtPoint(tapLocation)
//finally, we print out the value
print(indexPath)
//we could even get the cell from the index, too
let cell = self.tableView.cellForRowAtIndexPath(indexPath!)
cell.textLabel?.text = "Hello, Cell!"
}
Update:
Это показывает, как добавить распознаватель жестов в представление, через которое мы получаем indexPath
cell
(item
), который был дважды использован.
Вызывается функция обратного вызова, в пределах которой мы могли бы проверить, был ли задействован cell
(item
), который нам интересен.
override func viewDidLoad()
{
super.viewDidLoad()
let doubleTaps = UITapGestureRecognizer(target: self, action: "doubleTapTriggered:")
doubleTaps.numberOfTapsRequired = 2
self.view.addGestureRecognizer(doubleTaps)
}
func doubleTapTriggered(sender : UITapGestureRecognizer)
{
var tapLocation = sender.locationInView(self.collectionView)
var indexPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!
if let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
{
if(cell.tag == 100)
{
print("Hello, I am cell with tag 100")
}
else if(cell.tag == 99)
{
print("Hello, I am cell with tag 99")
//We could do something, then, with the cell that we are interested in.
//I.e., cell.contentView.addSubview(....)
}
}
}
Другое обновление:
Так как кажется, что вы добавляете распознаватель жестов, который требует двойных ответвлений для всех ячеек, что говорит мне, что вас интересует любая ячейка, которая была дважды нажата; и поэтому нам не нужно какое-либо условие для проверки того, являются ли ячейки теми, кого мы интересуем, потому что все они есть.
И так:
func doubleTapTriggered(sender : UITapGestureRecognizer)
{
var tapLocation = sender.locationInView(self.collectionView)
var indexPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!
name = imageArray[indexPath]
self.performSegueWithIdentifier("segue", sender: nil)
}
Ответ 2
Лучший способ добиться того, что вы пожелаете, - получить надзор за жестом вашего крана, это даст вам правильный indexPath. Попробуйте следующее:
func doubleTap(sender: UITapGestureRecognizer) {
let point = sender.view
let mainCell = point?.superview
let main = mainCell?.superview
let cell: myViewCell = main as! myViewCell
let indexPath = collectionView.indexPathForCell(cell)
}
Вы можете увеличить или уменьшить супервизор в зависимости от уровня иерархии.
Ответ 3
Все, что вам нужно сделать, это вызвать его без использования каких-либо параметров в строковом литерале.
var gestureDoubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
:
указывает компьютеру, что вы используете функцию с параметром, и которая создается где-то еще.
Надеюсь, что это поможет:)
Ответ 4
Как описано в документах разработчика Apple, параметр действия должен принимать
действие:: -Селектор, который идентифицирует метод, реализованный мишенью для обработки жестов, распознаваемых приемником. Селектор действий должен соответствовать сигнатуре, описанной в обзоре классов. Значение NULL недопустимо.
И действительные сигнатуры метода действия, описанные в UIGestureRecognizer.h, следующие:
//- (void) handleGesture; // - (void) handleGesture: (UIGestureRecognizer *) gestureRecognizer;
В принципе, вы не сможете отправлять что-либо еще в качестве параметра, кроме gestureRecognizer.