手勢是蘋果手機相當有趣的功能。下面我們就為開發者介紹一個為 UICollectionViewCell 綁定長按(long press)手勢的實例。
手勢綁定是最常用的功能之一,但沒有經驗的朋友第一次用 Swift 對 UICollectionView 中的每個 cell 綁定手勢時,往往會有些茫然。若對 Swift 手勢與 collectionView 的實作還不夠熟悉,建議先了解相關基礎,剩下的重點就是——如何為每個 UICollectionViewCell 綁定手勢。
首先得實作代理:
class ViewController:
UIViewController,
UICollectionViewDelegateFlowLayout,
UICollectionViewDataSource,
UIGestureRecognizerDelegate //手勢的代理
{
......
}
為每個 cell 實作手勢綁定的程式碼:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("newCell", forIndexPath: indexPath) as myCollectionViewCell
cell.backgroundColor=UIColor.blackColor()
var z: AnyObject! = dataArr[indexPath.row].valueForKey("zhangdanri")
var h: AnyObject! = dataArr[indexPath.row].valueForKey("huankuanri")
cell.textLabel?.text = "(z)~(h)"
cell.textLabel1?.text=dataArr[indexPath.row].valueForKey("bank") as? String
//這個tag是很有用的
cell.tag = indexPath.row
//最重要是下面這三行,記住是在這裡綁定手勢的
lp = UILongPressGestureRecognizer(target: self, action: Selector("longPress:"))
lp.delegate = self
cell.addGestureRecognizer(lp)
return cell
}
實作 long press 的回呼函式:
func longPress(recognizer: UILongPressGestureRecognizer){
//這就是你當前選中的cell的數組下標
var index = recognizer.view!.tag
if(recognizer.state == .Began)//很重要!!就是按0.5秒觸發事件的開始
{
.....
}
}
每個事件都有狀態,狀態也是一種過程:開始→改變→結束。如果上面的程式碼不做開始判斷,長按 0.5 秒後你的實際程式碼會執行好幾次!狀態包含 Began、Changed、Ended、Cancelled、Failed。