我有一個簡單的應用程序,其中包含CollectionView
及其中的項目。 長按cell
彈出UIView
出現一個TextField
和一個選項將其保存在對應於cell
array
。將手勢識別器功能中的變量傳遞給IBAction
這裏是代碼(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
}
}
試圖解決的問題在幾個方面:
在定義一個變量View Controller希望函數返回值並將其保存在全局變量中。 但是,後來從Apple發現, 「函數不能具有比其參數類型和返回類型更高的訪問級別,因爲該函數可用於其構成類型不可用於周圍代碼的情況。」 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
我試圖把按鈕的選擇功能碼長按手勢功能的內部,使得它的返回值是容易獲得的。但是,我無法調用Selector函數,因爲它在另一個函數中。
此外,我試着返回長按手勢功能的值,並在保存按鈕的IBAction中使用它。但是,爲此,我需要再次調用
handleLongPress
,然後longPressedPoint
被檢測爲保存按鈕內部。因此,是nil
和應用程序崩潰。
有人可以幫我...
這更好。它像一個魅力。非常感謝! –
謝謝你提醒我確保'rowOfLongPressedItem'不是'nil'。 –
儘管這段代碼有效,但我試圖理解它爲什麼起作用。 基於「函數不能具有比其參數類型和返回類型更高的訪問級別,因爲該函數可用於其構成類型不可用於周圍代碼的情況。」 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html 這段代碼不應該工作,不是嗎。 'assignRowOfLongPressedItem'如何保存作爲全局變量的'rowOfLongPressedItem'? –