使用平移手势选择多个表格视图单元格

Posted

技术标签:

【中文标题】使用平移手势选择多个表格视图单元格【英文标题】:Using a pan gesture to select multiple tableview cells 【发布时间】:2018-12-05 08:45:09 【问题描述】:

我正在尝试在表格视图上实现平移手势,以便在平移时选择多个单元格

我遇到的问题是当用户平移表格中的最后一个可见单元格时让 tableview 滚动到下一个单元格,或者当用户平移第一个可见单元格时滚动到上一个单元格

目前,当我的平移到达表中最后一个可见或第一个可见行时,它会为下一行设置动画,但仅针对前 2 或 3 行,然后停止滚动

经过一番挖掘,似乎是因为 panGesture 没有被调用,因为用户的手指在桌子边缘是静止的。

一旦平底锅到达桌子的顶部或底部边缘,我将如何保持表格滚动?

这是我当前的代码:

import UIKit

class MyView: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate 


    var lastSelectedCell = IndexPath()
    var gesturePan: UIPanGestureRecognizer!

    var totalRows = 100


    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() 
        super.viewDidLoad()

        //setup table gestures
        addGesturesToTable()

    







extension MyView

//MARK: - Tableview code
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return totalRows



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let lab = cell.viewWithTag(1) as! UILabel
    lab.text = "\(indexPath.row)"
    return cell






extension MyView

//MARK: - Gesture code
func addGesturesToTable() 
    tableView.canCancelContentTouches = false
    tableView.allowsMultipleSelection = true

    //add long press gesture to initiate pan
    let gestureLongPress = UILongPressGestureRecognizer(target: self, action: #selector(enablePan))
    gestureLongPress.minimumPressDuration = 0.25
    gestureLongPress.delaysTouchesBegan = true
    gestureLongPress.delegate = self
    tableView.addGestureRecognizer(gestureLongPress)

    //add pan gesture to select cells on drag
    gesturePan = UIPanGestureRecognizer(target: self, action: #selector(userPanned(_:)))
    gesturePan.isEnabled = false
    gesturePan.delegate = self
    tableView.addGestureRecognizer(gesturePan)




//LongPress gesture(to enable pan)
@objc func enablePan() 
    gesturePan.isEnabled = true



//Pan gesture
@objc func userPanned(_ panGesture: UIPanGestureRecognizer) 

    //if starting to pan
    if panGesture.state == .began 
        tableView?.isUserInteractionEnabled = false
        tableView?.isScrollEnabled = false


    //if pan position is changed
    else if panGesture.state == .changed 

        //get indexPath at pan location
        let location: CGPoint = panGesture.location(in: tableView)
        if let indexPath: IndexPath = tableView?.indexPathForRow(at: location) 

            //if the index path.row is the first or last row of the data set
            if(indexPath.row >= totalRows - 1 || indexPath.row <= 0)
               print("data start/end reached")

            //otherwise
            else

                //get pan direction
                var direction: String!
                let velocity = panGesture.velocity(in: tableView)
                if(velocity.y > 0)
                    direction = "Down"
                else
                    direction = "Up"
                

                //if it's a new cell
                if indexPath != lastSelectedCell 

                    //select/deselect it
                    self.selectPannedCell(indexPath, selected: true, location: location, panDirection: direction)

                    //update last selected cell
                    lastSelectedCell = indexPath
                
            
        

    //if pan gesture is ending
    else if panGesture.state == .ended 

        //re-enable tableview interaction
        tableView.isScrollEnabled = true
        tableView.isUserInteractionEnabled = true

        //disable pan gesture
        panGesture.isEnabled = false
    










//select/deselect the panned over cell
func selectPannedCell(_ indexPath: IndexPath, selected: Bool, location: CGPoint, panDirection: String) 
    if let cell = tableView.cellForRow(at: indexPath) 

        //if cell is already selected
        if cell.isSelected 

            //deselect row
            tableView.deselectRow(at: indexPath, animated: true)


            //if panning down
            if(panDirection == "Down")

                //if it's the last cell
                if(indexPath >= tableView.indexPathsForVisibleRows![(tableView.indexPathsForVisibleRows?.count)!-1])

                    //scroll to the next cell after the last visible
                    let scrollToIndex = IndexPath(row: indexPath.row + 1, section:0)
                    tableView.scrollToRow(at: scrollToIndex, at:
                        UITableViewScrollPosition.bottom, animated: true)
                

                //if panning up
            else

                //if it's the first cell
                if(indexPath <= tableView.indexPathsForVisibleRows![0])

                    //scroll to the previous cell before first visible
                    let firstIndex = IndexPath(row: indexPath.row - 1, section:0)
                    tableView.scrollToRow(at: firstIndex, at:
                        UITableViewScrollPosition.top, animated: true)
                
            


         else 


            //select row
            tableView.selectRow(at: indexPath, animated: true, scrollPosition: UITableViewScrollPosition.none)

            //if panning down
            if(panDirection == "Down")


                //if it's the last cell
                if(indexPath >= tableView.indexPathsForVisibleRows![(tableView.indexPathsForVisibleRows?.count)!-1])

                    //scroll to the next cell after the last visible
                    let lastIndex = IndexPath(row: indexPath.row + 1, section:0)
                    tableView.scrollToRow(at: lastIndex, at:
                        UITableViewScrollPosition.bottom, animated: true)

                

            else

                //if it's the first cell
                if(indexPath <= tableView.indexPathsForVisibleRows![0])

                    //scroll to the previous cell before first visible
                    let firstIndex = IndexPath(row: indexPath.row - 1, section:0)
                    tableView.scrollToRow(at: firstIndex, at:
                        UITableViewScrollPosition.top, animated: true)

                
            

        

    




提前致谢

【问题讨论】:

【参考方案1】:

快速示例如何在您的情况下实现它,我认为您可以轻松地满足您的需求。

var continueScrollToBottom: Bool = false
var continueScrollToTop: Bool = false

@objc func updatePanGesture(_ sender: UIPanGestureRecognizer) 
    switch sender.state 
    case .changed:

        continueScrollToBottom = false
        continueScrollToTop = false

        // If you reach to the top make scroll constant
        // You can define there another condition which more suitable for you
        if sender.location(in: self.view).y < 200 
            continueScrollToTop = true
            continueScrollToBottom = false
            self.startScrollToTop()
            return
        

        // If you reach to the bottom make scroll constant
        // You can define there another condition which more suitable for you
        if sender.location(in: self.view).y > 350 
            continueScrollToBottom = true
            continueScrollToTop = false
            self.startScrollToBottom()
            return
        

    case .ended:
        continueScrollToBottom = false
        continueScrollToTop = false

    case .cancelled:
        continueScrollToBottom = false
        continueScrollToTop = false

    default:
        break
    


func startScrollToBottom() 
    if continueScrollToBottom 
        if let last = tableView.indexPathsForVisibleRows?.last, last.row+1 < countOfRows  
            let showNext = IndexPath(row: last.row+1, section: last.section)
            tableView.scrollToRow(at: showNext, at: .bottom, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.3) 
                self.startScrollToBottom()
            
        
    


func startScrollToTop() 
    if continueScrollToTop 
        if let first = tableView.indexPathsForVisibleRows?.first, first.row-1 > 0  
            let showNext = IndexPath(row: first.row-1, section: first.section)
            tableView.scrollToRow(at: showNext, at: .top, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.3) 
                self.startScrollToTop()
            
        
    

【讨论】:

感谢Gkolunia的回答,我用类似的方案解决了,但是用了一个定时器来触发连续滚动

以上是关于使用平移手势选择多个表格视图单元格的主要内容,如果未能解决你的问题,请参考以下文章

防止多个可平移的表格视图单元格被平移

处理 UITableView 单元格上的平移手势

自定义表格视图单元格中特定元素的手势

我可以在 tableviewcell 中发现 tableview 手势识别器的状态吗

动画时 UITableView 剪辑到边界

使用滑动手势在 swift3 中编辑表格视图单元格