【问题标题】:How to get indexPath of Row, from UISwitch Toggle如何从 UISwitch Toggle 获取行的 indexPath
【发布时间】:2022-01-04 00:22:43
【问题描述】:

我有以下用户界面:

我想检索我点击开关所在行的indexPath

例如,如果我点击开关Task 1,我想将结果存储到一个变量中。在此示例中,该变量将保存字符串“Task 1”。我怎样才能做到这一点?

这里有一些重要的事情要知道。

我正在创建一个自定义单元格,并为此创建了一个自定义类。

CellTask.swift

import UIKit
import FirebaseDatabase

class TaskCell: UITableViewCell {
    @IBOutlet weak var completed: UISwitch!
    @IBOutlet weak var taskLabel: UILabel!
    
    private let database = Database.database().reference()
    var tcTitle: String = ""
    
    func setTaskTitle(task: Task){
        taskLabel.text = task.title
    }

    @IBAction func completedTask(_ sender: UISwitch) {
        
        if sender.isOn{
            taskLabel.textColor = UIColor.red
        }else{
            taskLabel.textColor = UIColor.black
        }
    }
}
  • tcTitle 将从主 ViewController 中获取单元格的名称

这是我在cellForRowAt函数中尝试做的,但它不起作用:

let uv = TaskCell()
uv.tcTitle = task

这是 TableView 的完整代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let row = taskTitles[indexPath.row]
    
    let tc = storyboard?.instantiateViewController(identifier: "UpdateTask") as! TaskUpdateViewController
    tc.titleOfTask = row
    
    tc.modalPresentationStyle = .fullScreen
    
    //wrap the new view controller in a navigation controller (this adds the top bar)
    let navigationController = UINavigationController(rootViewController: tc)
    
    // so you can actually see the Create a Task text,
    navigationController.navigationBar.barStyle = .default
    
    present(navigationController, animated: true)
    
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return taskTitles.count
    
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let task =  taskTitles[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell") as! TaskCell
    cell.taskLabel.text = task
    
    let uv = TaskCell()
    uv.tcTitle = task
    
    
    
    return cell
}

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

也许这不是最简单的方法,但 celldelegate 可以提供帮助。您必须将数据向下发送到单元格,然后您可以“向上拉”并将选定的切换值附加到数组中。

让我们创建委托协议:

protocol ToggleIndexDelegate:AnyObject {
func getIndex(_ cell:MyCell, index:IndexPath)
}

然后,将您需要的所有内容发送到单元格中:

  lazy var tableView: UITableView = {
    let tv = UITableView(frame: .zero)
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.delegate = self
    tv.dataSource = self
    tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    tv.register(MyCell.self, forCellReuseIdentifier: "toggle")
    return tv
}()
let defaultArray = ["one", "two", "three"]
var selectedarray:[String] = []

//MARK: - Lifecycle

override func viewDidLoad() {
    super.viewDidLoad()
    
}

//MARK: - TableView

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return  defaultArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "toggle", for: indexPath) as! MyCell
    cell.textLabel?.text = defaultArray[indexPath.row]
    cell.delegate = self
    cell.indexP = indexPath
    return cell
}


//MARK: - Load

override func loadView() {
    super.loadView()
    
    view.addSubview(tableView)
    tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}

您的自定义单元:

class MyCell: UITableViewCell {

let mytoggle = UISwitch()

weak var delegate:ToggleIndexDelegate?
var indexP:IndexPath?

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    accessoryView = mytoggle
    mytoggle.addTarget(self, action: #selector(toggleHandler), for: .valueChanged)
    
}


@objc func toggleHandler(){
    
    if let safedelegate = delegate, let safeindex = indexP{
        safedelegate.getIndex(self, index: safeindex)
    }
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

然后在VC中调用委托方法

func getIndex(_ cell: MyCell, index: IndexPath) {
    
    
    if selectedarray.contains(defaultArray[index.row]){
        selectedarray.removeAll(where: {$0 == defaultArray[index.row]})
    } else{
        selectedarray.append(defaultArray[index.row])
    }
    print(selectedarray)
}

【讨论】:

  • 抱歉,由于某种原因我无法复制整个代码,但这会起作用,只需将此代码复制到一个空的 Viewcontroller 中,然后运行应用程序。
猜你喜欢
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2012-03-02
  • 2018-02-02
  • 1970-01-01
相关资源
最近更新 更多