【发布时间】:2016-10-04 07:08:54
【问题描述】:
我有一个简单的应用程序,其中包含 CollectionView 和项目。
长按cell 时,弹出UIView 会出现TextField 和将其保存在与cell 对应的array 中的选项。
这是代码(buttons 和 gestures 已在 viewDidLoad() 方法中正确添加):
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var longPressedPoint: CGPoint?
public var rowOfLongPressedItem: Int? = nil
func handleLongPress(longPressRecognizer: UILongPressGestureRecognizer) -> Int {
print("LONG PRESS Gesture Recognized")
notePopup.hidden = false
longPressedPoint = longPressRecognizer.locationInView(longPressRecognizer.view)
var indexPathOfLongPressedCell = self.itemCollectionView.indexPathForItemAtPoint(longPressedPoint!)
rowOfLongPressedItem = (indexPathOfLongPressedCell?.row)
print("rowOfLongPressedItem -> .\(rowOfLongPressedItem)")
return rowOfLongPressedItem!
}
func saveNoteButtonTapped(rowOfLongPressedItem: Int) {
print("rowOfLongPressedItem when Save button is tapped -> .\(rowOfLongPressedItem)")
//Can’t go further down as rowOfLongPressedItem is NOT available from “handleLongPress” function…
var selectedItem = ItemsList[rowOfLongPressedItem]
selectedItem.counts += 1
var latest = selectedItem.counts - 1
selectedItem.timestamp.append(NSDate())
selectedItem.note.append(noteTextField.text)
ItemsList[rowOfLongPressedItem] = selectedItem
print(".\(selectedItem.title) has been tapped .\(selectedItem.counts)")
print("The latest tap on .\(selectedItem.title) is at .\(selectedItem.timestamp[latest])")
print("The note .\(noteTextField.text) has been added")
notePopup.hidden = true
}
}
尝试通过几种方式解决问题:
在视图控制器中定义一个变量,希望该函数将返回值并将其保存在全局变量中。 但是,后来从苹果那里发现 “一个函数的访问级别不能高于其参数类型和返回类型,因为该函数可用于其组成类型对周围代码不可用的情况。” https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
我尝试将按钮的选择器功能代码放入长按手势功能中,以便轻松获得它的返回值。但是,我无法调用 Selector 函数,因为它位于另一个函数中。
另外,我尝试返回长按手势功能的值并在保存按钮的 IBAction 中使用它。但是,为此我需要再次调用
handleLongPress,然后将longPressedPoint检测为内部保存按钮。因此,indexPathOfLongPressedCell是nil,应用程序崩溃。
谁能帮帮我...
【问题讨论】:
标签: swift uicollectionview uigesturerecognizer return-type ibaction