UITableView具有使用Realm和Swift的按字母顺序排列的多个节,并且多个标签与同一数据连接

过去尝试解决这一问题已有十多天了,但仍然没有运气来解决这种情况。

我正在尝试根据“ ExerciseName”列的名称,按字母顺序从A-Z向表视图添加节。我也有一个“ BodyPartName”,“ CategoryName”?每个“ ExerciseName”的数据列。

我想填充A-Z中的部分,并在同一部分中将ExerciseName排序为BodyPartName和CategoryName,以用于同一行中的其他标签。

我成功地在A-Z部分实现了ExerciseName,但是无法将BodyPartName和CategoryName添加到同一行的其他标签中。请帮忙!

预期结果

A

Abs“(核心)”

手臂按“(武器)”“(哑铃)”

B

二头肌卷曲“(手臂)”“(杠铃)”

后退扩展名“(后退)”“(机器)”

无法为同一行填充“ BodyPartName”标签和“ CategoryName”标签。

这是我的领域数据模型:

class Exercises: Object
{

    @objc dynamic var ExerciseID = 0
    @objc dynamic var ExerciseName = ""
    @objc dynamic var BodyPartName = ""
    @objc dynamic var CategoryName: String? = ""

    //Adding Parent Table BodyPart & Category.
    var parentBodyParts = LinkingObjects(fromType: BodyParts.self,property: "exercises")
    var parentCategory = LinkingObjects(fromType: Category.self,property: "category")

}

我的代码:

let realm = try! Realm()
var exerciseArray: Results<Exercises>!

override func viewDidLoad()
    {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "customCell",bundle: nil),forCellReuseIdentifier: cellID)
        sectionFunction()
    }

var sectionDictionary = [String:[String]]()
var sectionTitles = [String]()

func sectionFunction()
{
     exerciseArray = realm.objects(Exercises.self).sorted(byKeyPath: "ExerciseName")

    for section in exerciseArray
    {
        let sectionKey = String(section.ExerciseName.prefix(1)) 

        if var sectionValues = sectionDictionary[sectionKey]
        {
            sectionValues.append(section.ExerciseName) // Adding ExerciseNames to the Keys
            sectionDictionary[sectionKey] = sectionValues
        }
        else
        {
            sectionDictionary[sectionKey] = [section.ExerciseName]
        }
    }
    sectionTitles = [String](sectionDictionary.keys)
    sectionTitles = sectionTitles.sorted(by: {$0 < $1}) // Alphabetical order for Keys:Values
}

override func numberOfSections(in tableView: UITableView) -> Int
    {
        return sectionTitles.count
    }


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


    override func sectionIndexTitles(for tableView: UITableView) -> [String]?
    {
        return sectionTitles
    }


    override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int
    {
        let sectionKey = sectionTitles[section]
        if let sectionValues = sectionDictionary[sectionKey]
        {
            return sectionValues.count
        }
        return 0
       // return exercises.filter("ExerciseName == %@",sectionNames[section]).count
    }

    // Register custom cell for Table View
    let cellID = "customCell"

    override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
      let cell = tableView.dequeueReusableCell(withIdentifier: cellID,for: indexPath) as! customCell

        let sectionKey = sectionTitles[indexPath.section]
        if let sectionValues = sectionDictionary[sectionKey]
        {
          exerciseArray = realm.objects(Exercises.self).sorted(byKeyPath: "ExerciseName")

            cell.exerciseName.text = sectionValues[indexPath.row]
            cell.bodyPartName.text = exerciseArray.filter("ExerciseName == %@",sectionValues[indexPath.row]) [indexPath.row].BodyPartName
            cell.categoryName.text = exerciseArray.filter("ExerciseName == %@",sectionValues[indexPath.row])  [indexPath.row].CategoryName ?? ""
            cell.backgroundColor = .clear
        }
        return cell
    }

自定义单元格:

class customCell: UITableViewCell {

    @IBOutlet weak var exerciseName: UILabel!
    @IBOutlet weak var bodyPartName: UILabel!
    @IBOutlet weak var categoryName: UILabel!

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

override func setSelected(_ selected: Bool,animated: Bool) {
    super.setSelected(selected,animated: animated)   
}   

}

fly_x 回答:UITableView具有使用Realm和Swift的按字母顺序排列的多个节,并且多个标签与同一数据连接

问题中的代码存在许多问题,因此,我没有试图剖析它们,而是提供一个可能有帮助的示例。

假设我们在Realm中存储了一堆水果。我们想使用部分在表格视图中按字母顺序显示那些

A
   Apple
B
   Banana

第一段代码是一个结构,用于保存节标题,然后保存该节中的一系列水果。另外,一个类fruitNameArray将用作我们的tableView数据源,其中包含所有FruitStructs。

struct FruitStruct {
    var sectionTitle = ""
    var fruitNameArray = [String]()
}

var fruitDataSource = [FruitStruct]()

我正在使用数组保存初始数据,但是在您的情况下,它可能是从Realm填充的Realm结果对象。这是通过viewDidLoad调用的,以将我们的数据整理到dataSource数组中

func setupDataSourceData() {
    let fruitArray = ["Apple","Pear","Banana","Bing Cherry","Grape","Orange","Plum","Watermelon","Cantelope"]

    let allFirstChars = fruitArray.map { String($0.prefix(1)) } //get all first chars for section titles
    let sectionTitles = Array(Set(allFirstChars)).sorted() //eliminate dups and sort

    //iterate over the unique section titles and get the fruits that are in that section
    // sort and then craft structs to hold the title and the associated fruits
    sectionTitles.forEach { firstChar in
        let results = fruitArray.filter { $0.prefix(1) == firstChar }
        let sortedFruits = results.sorted()
        let fruit = FruitStruct(sectionTitle: firstChar,fruitNameArray: sortedFruits)
        fruitDataSource.append(fruit)
    }

    for fruitData in fruitDataSource {
        print(fruitData.sectionTitle)
        let fruits = fruitData.fruitNameArray
        for fruitName in fruits {
            print("  \(fruitName)")
        }
    }
}

然后,tableView需要有4个功能来显示各节,然后显示各节中的行。您似乎拥有这4个,但可能不需要另外一个sectionIndexTitles

//
//handle sections
//
func numberOfSections(in tableView: UITableView) -> Int {
    return self.fruitDataSource.count
}

func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
    let title = self.fruitDataSource[section].sectionTitle
    return title
}

//
//handleTableView rows
//
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    let rowsInSection = self.fruitDataSource[section].fruitNameArray.count
    return rowsInSection
}

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier",for: indexPath)
    let text = self.fruitDataSource[indexPath.section].fruitNameArray[indexPath.row]
    cell.textLabel?.text = text
    return cell
}

请注意,由于正在填充tableView,因此我不执行任何过滤和其他任何操作。该部分代码需要快速且精益于UI,以尽可能地响应。

我刚得到一个字符串

let text = self.fruitDataSource[indexPath.section].fruitNameArray[indexPath.row]

但是在您的情况下,您可能需要返回一个运动对象,然后可以在其中获取exerciseName和bodypartName,然后在自定义cellView中分配这些对象

最佳实践注意:类属性应小写-exerciseName,而不是大写,exerciseName。类和结构名称通常大写。

本文链接:https://www.f2er.com/2880130.html

大家都在问