Подтвердить что ты не робот

Галочка UITableViewCell для включения и выключения при нажатии

Я работаю над столом

Я хочу иметь возможность нажимать на каждую ячейку, и при нажатии она отображает галочку на ячейке

Теперь у меня есть код, который делает эту работу:

// checkmarks when tapped

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let section = indexPath.section
    let numberOfRows = tableView.numberOfRowsInSection(section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
            cell.accessoryType = row == indexPath.row ? .Checkmark : .None
        }
    }
}

но этот код выбирает только 1 ячейку внутри раздела (у меня есть 5 разделов)

Мне нужно, чтобы выбрать любую ячейку в любом месте

Также, когда я перетаскиваю свой экран вверх и вниз, я теряю галочкой

viewcontroller.swift

class ViewController: UIViewController, UITableViewDataSource {                        //class and subclass                  |)
//---------------------------------------------------------------------------------------------------------------------------/
    // Variable and constant, also IBAOutlet

    let section1 =
       ["this is used",
        "this is used to test",
        "this is used to test the lenght",
        "this is used to test the lenght of the text",
        "this is used to test the lenght of the text",
        "this is used to test the lenght of the text",
        "this is used to test the lenght of the text",
        "this is used to test the lenght of the text",
        "this is used to test the lenght of the text",]
    let section2 =
       ["this is used to test the lenght of the text"]
    let section3 =
       ["this is",
        "this is ",]


    @IBOutlet weak var scoreshow: UILabel!
    @IBOutlet weak var reset: UIButton!
    @IBOutlet weak var tableView: UITableView!

// --------------------------------------------------------------------------------------

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

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }
//----------------------------------------------------------------------------------------
    // checkmarks when tapped

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark
            {
                cell.accessoryType = .None
            }
            else
            {
                cell.accessoryType = .Checkmark
            }
        }    
    }
//----------------------------------------------------------------------------------------
    //number of sections for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 5
    }
//----------------------------------------------------------------------------------------
    //Calculate the amount of rows

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.section1.count;
    }
//----------------------------------------------------------------------------------------
    //Cells text label and config

    func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
        cell.textLabel!.text = section1[indexPath.row]
        cell.textLabel!.numberOfLines = 0

        return cell
    }

//----------------------------------------------------------------------------------------

    @IBAction func resetswitch(sender: UIButton) {




    }
//----------------------------------------------------------------------------------------

}
4b9b3361

Ответ 1

Swift> 3.0

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .none
    }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .checkmark

    }
}

Я решил с помощью двух функций Swift: didSelectRowAtIndexPath и didDeselectRowAtIndexPath.

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.accessoryType = .None
    }
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.accessoryType = .Checkmark

    }
}

Чтобы это работало правильно, добавьте строку кода в функцию cellForRowAtIndexPath, чтобы выбрать строку, когда табличное представление рисуется на экране, в противном случае didDeselectRowAtIndexPath не будет вызываться при первом выборе другой строки. Вот так:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cellData", forIndexPath: indexPath) 
    if (some condition to initially checkmark a row)
        cell.accessoryType = .Checkmark
        tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Bottom)
    } else {
        cell.accessoryType = .None
    }

    return cell
}

Ответ 2

Попробуйте следующее:

var checked = [Bool]() // Have an array equal to the number of cells in your table


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

    //configure you cell here.
    if !checked[indexPath.row] {
        cell.accessoryType = .None
    } else if checked[indexPath.row] {
        cell.accessoryType = .Checkmark
    }
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        if cell.accessoryType == .Checkmark {
             cell.accessoryType = .None
             checked[indexPath.row] = false
        } else {
             cell.accessoryType = .Checkmark
             checked[indexPath.row] = true
        }
    }    
}

В reset все флажки:

func resetChecks() {
   for i in 0.. < tableView.numberOfSections {
       for j in 0.. < tableView.numberOfRowsInSection(i) {
            if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
               cell.accessoryType = .None
            }
       }
   }
}

Ответ 3

UITableView сохраняет выбранное состояние для одного или нескольких выборов. Поэтому у ИМО должна быть очень веская причина для сохранения где-то целого параллельного состояния. Если вы хотите просто изменить внешний вид ячейки в зависимости от состояния выбора, сделайте это в ячейке.

В вашем подклассе UITableViewCell переопределите setSelected следующим образом:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    self.accessoryType = selected ? .checkmark : .none
}

Не нужно использовать какие-либо методы делегирования табличного представления.

Примечание. Вы должны вызвать super.setSelected, иначе ячейка не будет правильно сохранять выбранное состояние.

Ответ 4

Swift 3.0
Использование только одной функции для простоты

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
        if cell.accessoryType == .checkmark {
            cell.accessoryType = .none
        } else {
            cell.accessoryType = .checkmark
        }
    }   
}

Ответ 5

Swift 3.0

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .checkmark
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .none
    }
}

Ответ 6

Swift 4.0, теперь все вместе:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var yourData = ["Cool","Sweet","Awesome"]

var checked = [Bool]()

override func viewDidLoad() {
    super.viewDidLoad()
    checked = Array(repeating: false, count: yourData.count)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchData.count
}
func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

    //configure you cell here.
    if checked[IndexPath.row] == false{
        cell.accessoryType = .none
    } else if checked[IndexPath.row] {
        cell.accessoryType = .checkmark
    }

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
        if cell.accessoryType == .checkmark {
            cell.accessoryType = .none
            checked[indexPath.row] = false
        } else {
            cell.accessoryType = .checkmark
            checked[indexPath.row] = true
        }
    }
}

}

Ответ 7

Swift 5.0

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    if let cell = tableView.cellForRow(at: indexPath) {
        resetChecks()
        cell.accessoryType = .checkmark
    }
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
}

func resetChecks() {
    for i in 0..<tableView.numberOfSections {
        for j in 0..<tableView.numberOfRows(inSection: i) {
            if let cell = tableView.cellForRow(at: IndexPath(row: j, section: i)) {
                cell.accessoryType = .none
            }
        }
    }
}

Ответ 8

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if self.checkedIndex == indexPath.row{

    }else{
        let cell = tableView.cellForRow(at: indexPath)
        cell?.accessoryType = .checkmark
        let indexPathh = IndexPath(row: checkedIndex, section: 0)
        let UnCheckCell = tableView.cellForRow(at: indexPathh)
        UnCheckCell?.accessoryType = .none
        checkedIndex = indexPath.row
    }
}

Ответ 9

Обновлено в Swift 4.2 Каждый новый выбор Удалить предыдущую галочку

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(self.coloursArray[indexPath.row])

     self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
}

Ответ 10

Поскольку я не видел никого в этом списке, вы можете создать пользовательский UITableViewCell, который будет переключать флажок с выбором, переопределяя его метод setSelected() и по умолчанию .selectionStyle равняясь .gray:

class CheckableTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .gray
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        accessoryType = selected ? .checkmark : .none
    }
}