ios - Swift - 如何创建正确的 sectionForSectionIndexTitle?

标签 ios swift xcode uitableview indexing

我有一个包含完整字母表的部分索引 - 然而,我表格中的部分仅包含几个字母(例如 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
}

最佳答案

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

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
}

关于ios - Swift - 如何创建正确的 sectionForSectionIndexTitle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911998/

相关文章:

ios - 从 ImplicitlyUnwrappedOptional<Swift.AnyObject> 到 Array<AnyObject> 的午睡 Swift 转换

ios - 带有图像的 UITableViewCell 动态高度

c++ - 在 Xcode 调试器中自动显示 C++ 对象的属性

ios - 如何在 UITabBarController 中获取特定 UIViewController 的索引

ios - IBDesignable View 导致无休止的重建

swift - 在 SwiftUI 预览中绑定(bind) <Double>

iphone - NSArray removeObjectAtIndex 错误

ios - 我想放置具有不同标签文本颜色的选框标签

ios - 使用 case switch 而不是多个 if 语句来处理错误

objective-c - setRightBarButtonItems iOS5 不工作