【问题标题】:Swift - how to create correct sectionForSectionIndexTitle?Swift - 如何创建正确的 sectionForSectionIndexTitle?
【发布时间】:2016-08-12 07:12:32
【问题描述】:

我有一个包含完整字母表的部分索引 - 但是,我表中的部分只包含几个字母(例如 C、F、N、U)。

我想修改 sectionForSectionIndexTitle 以在手指滑过部分索引时正确显示正确的部分。我仍然不确定如何使用sections.append ...

感谢您的帮助。

这就是我的代码的样子:

Section.swift

struct Section
{
    var heading : String
    var items : [String]

    init(title: String, objects : [String]) {

        heading = title
        items = objects
    }
}

ViewController.swift

func updateSections(index : Int) {

    switch index {

    case 0:
        sections.append(Section(title: "C", objects: ["Czech Republic"]))
        sections.append(Section(title: "F", objects: ["France"]))
        sections.append(Section(title: "N", objects: ["Norway"]))
        sections.append(Section(title: "U", objects: ["USA"]))

    default: break
    }

    tableViewOutlet.reloadData()
}

let arrIndexSection = ["A","B","C","D", "E", "F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    if segmentedControlOutlet.selectedSegmentIndex == 0 {
        return arrIndexSection
    } else {
        return [""]
    }
}

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    let temp = arrIndexSection as NSArray
    return temp.indexOfObject(title)
}

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let section = sections[section]
    return section.items.count
}

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

【问题讨论】:

  • 你在哪里调用 updateSections() ?
  • 在很多地方(例如分段控件或 UISwipeGestureRecognizerDirection)。上面的代码只是与问题最相关的部分。
  • 您的问题是什么?我能提供什么帮助?

标签: ios swift xcode uitableview indexing


【解决方案1】:

在您的项目中尝试以下代码:

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    var tempIndex:Int = 0
    for str in arrIndexSection {
        if str == title {
            return tempIndex
        }
        tempIndex += 1
    }
    return 0
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2023-04-03
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多