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

Как заполнить два раздела в виде таблицы двумя различными массивами с помощью swift?

У меня есть два массива Data1 и Data2, и я хочу заполнить данные в каждом из них (они содержат строки) в виде таблицы в двух разных разделах. Первый раздел должен иметь заголовок "Некоторые данные 1", а второй раздел должен иметь название "KickAss".

У меня есть оба раздела, заполняющие данные из первого массива (но без заголовков).

Вот мой код:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rowCount = 0
        if section == 0 {
            rowCount = Data1.count
        }
        if section == 1 {
            rowCount = Data2.count
        }
        return rowCount
    }
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        let ip = indexPath
        cell.textLabel?.text = Data1[ip.row] as String
        return cell
    }

в методе cellForRowAtIndexPath, возможно ли мне определить раздел так или иначе, как в методе numberOfRowsInSection? Кроме того, как я могу предоставить заголовки для каждого раздела? Благодаря

4b9b3361

Ответ 1

Элементы TableView

Вы можете использовать многомерный массив. Например:

let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]]

Для количества разделов используйте:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return data.count
}

Затем, чтобы указать количество строк в каждом разделе, используйте:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count
}

Наконец, вам нужно настроить свои ячейки:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellText = data[indexPath.section][indexPath.row]

    //  Now do whatever you were going to do with the title.
}

Заголовки TableView

Вы можете снова использовать массив, но на этот раз с одним измерением:

let headerTitles = ["Some Data 1", "KickAss"]

Теперь, чтобы установить заголовки для разделов:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section < headerTitles.count {
        return headerTitles[section]
    }

    return nil
}

Приведенный выше код проверяет, есть ли название для этого раздела и возвращает его, в противном случае возвращается nil. Не будет заголовка, если количество заголовков в headerTitles меньше, чем количество массивов в data.

Результат

enter image description here

Ответ 2

Вы можете создать Struct для хранения данных, относящихся к разделу, в качестве альтернативы моему предыдущему ответу. Например:

struct SectionData {
    let title: String
    let data : [String]

    var numberOfItems: Int {
        return data.count
    }

    subscript(index: Int) -> String {
        return data[index]
    }
}

extension SectionData {
    //  Putting a new init method here means we can
    //  keep the original, memberwise initaliser.
    init(title: String, data: String...) {
        self.title = title
        self.data  = data
    }
}

Теперь в вашем контроллере просмотра вы можете настроить данные раздела так:

lazy var mySections: [SectionData] = {
    let section1 = SectionData(title: "Some Data 1", data: "0, 1", "0, 2", "0, 3")
    let section2 = SectionData(title: "KickAss", data: "1, 0", "1, 1", "1, 2")

    return [section1, section2]
}()

Заголовки разделов

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return mySections.count
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return mySections[section].title
}

По сравнению с моим предыдущим ответом вам теперь не нужно беспокоиться о том, чтобы сопоставить число headerTitles с числом массивов в data.

Элементы TableView

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return mySections[section].numberOfItems
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellTitle = mySections[indexPath.section][indexPath.row]

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = cellTitle

    return cell
}

Ответ 3

Вы можете определить, в каком разделе вы находитесь, посмотрев indexPath.section. Чтобы указать заголовки, переопределите функцию

func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String!

Ответ 4

В switch 4 или swift 5 вы можете использовать like.Here Пользовательский раздел заголовка с фильтром показан Изображение выглядит как ниже enter image description here

  1. создать проект
  2. Добавить представление таблицы
  3. создать ячейку UITableView
  4. Подключите метку к удобному виду & таблица с контроллером представления
  5. Добавьте приведенный ниже код

    import UIKit
    
    struct Category {
    let name : String
    var items : [[String:Any]]
    }
    
     class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
      @IBOutlet weak var txtName: UITextField!
    
     @IBOutlet weak var tableView: UITableView!
    
    var originalArr = [[String:Any]]();
    var recentArr = [[String:Any]]();
    var searchArrRes = [[String:Any]]()
    var searching:Bool = false
    
     //
    var sections = [Category]()
    
    override func viewDidLoad() {
      super.viewDidLoad()
    
    //Assign delegate  don't forget
    txtName.delegate = self
    tableView.delegate = self
    tableView.dataSource = self
    
    
    
    recentArr =   [
        ["name": "Enamul", "number": "+8800000003"],
        ["name": "Enam", "number": "+8800000004"]
    ]
    
    originalArr = [
        ["name": "abdul", "number": "+8800000001"],
        ["name": "abdin", "number": "+8800000002"],
        ["name": "Enamul", "number": "+8800000003"],
        ["name": "enam", "number": "+8800000004"],
        ["name": "Rafi", "number": "+8800000005"],
        ["name": "Ehaque", "number": "+8800000006"]
       ]
    
     //my array
      sections = [
          Category(name:"Recent", items:recentArr),
          Category(name:"ALL", items:originalArr)
          ]
    
          }
    
    
       func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
         }
    
     func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
          guard let tableView = view as? UITableViewHeaderFooterView else { return }
    
       tableView.textLabel?.textColor = UIColor.red
     }
    
     public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
    //input text
    let searchText  = textField.text! + string
    
    searchArrRes = self.originalArr.filter({(($0["name"] as! String).localizedCaseInsensitiveContains(searchText))})
    
    
    if(searchArrRes.count == 0){
        searching = false
    }else{
        searching = true
    }
    self.tableView.reloadData();
    
    return true
    }
    
    
      func numberOfSections(in tableView: UITableView) -> Int {
    if( searching == true){
        return 1
        }
       return self.sections.count
       }
    
      func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if( searching == true){
        return ""
       }
      return self.sections[section].name
      }
    
       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if( searching == true){
       return searchArrRes.count
    }else{
        let items = self.sections[section].items
        return items.count
      }
     }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_cell
      //  var dict = itemsA[indexPath.section]
    
    if( searching == true){
        var dict = searchArrRes[indexPath.row]
        cell.name.text = dict["name"] as? String
        cell.number.text = dict["number"] as? String
     }else{
        let items = self.sections[indexPath.section].items
        let item = items[indexPath.row]
        cell.name.text = item["name"] as? String
        cell.number.text = item["number"] as? String
    
        }
    
        return cell
         }
    
    
    }
    

Вы можете скачать полный исходный код с GitHub.GitHub https://github.com/enamul95/Custom_table_view_section.git