【问题标题】:how show user selected cell of tableview on longpress如何在长按上显示用户选择的表格视图单元格
【发布时间】:2019-07-19 11:51:38
【问题描述】:

您好,我在我的表格视图中添加UILongPressGesture,并且我已成功添加,但问题是如何显示该单元格已被选中,我的意思是我想更改所选单元格的颜色,当我再次长按所选单元格时,我想要取消选择单元格

我尝试在我的表格视图中添加长按代码并在 LongPress 上分配代表这是我的代码

 @objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

        if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {

            let touchPoint = longPressGestureRecognizer.location(in: self.tblList)
            if let indexPath = tblList.indexPathForRow(at: touchPoint) {


            }
        }
    }

viewDidload() 我正在编写这段代码

let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(SMSChatViewController.longPress(_:)))
        longPressGesture.minimumPressDuration = 1.0 // 1 second press
        longPressGesture.delegate = self
        self.tblList.addGestureRecognizer(longPressGesture)

所以从这段代码中我可以选择单元格,但是如何向用户显示单元格已被选中我不知道该怎么做

所以我只想这样当用户长按而不是单元格颜色更改并设置为选中然后再次长按而不是取消选择具有原始颜色的单元格

【问题讨论】:

    标签: ios swift uitableview uilongpressgesturerecogni


    【解决方案1】:

    当 longPressGesture 被识别时,你只改变单元格的 backgroundColor 怎么样?像这样的:

    @objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
    
            if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
    
                let touchPoint = longPressGestureRecognizer.location(in: self.tblList)
                if let indexPath = tblList.indexPathForRow(at: touchPoint) {
                    let cell = tblList.cellForRow(at: indexPath)
                    if (cell.isSelected) {
                        cell.backgroundColor = UIColor.clear // or whatever color you need as default
                        cell.setSelected(false, animated: true)
                    } else {
                        cell.backgroundColor = UIColor.orange
                        cell.setSelected(true, animated: true)
                    }
    
                }
            }
        }
    

    如果您需要澄清或我误解了某件事,请告诉我,我将编辑我的答案。

    【讨论】:

    • 好的,我知道了,但是如果我想取消选择该单元格并更改我无法做到的颜色,我希望您能理解我的问题吗?
    • 谢谢你的回答为我工作!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多