【问题标题】:Type NSAttributedString has no subscript members in tableViewNSAttributedString 类型在 tableView 中没有下标成员
【发布时间】:2017-02-03 19:35:41
【问题描述】:

我有一个带有 X 项的 AttributedString 数组和一个将显示该数组的 tableView,并且对于数组中的每个项,表中都会有一个 Section。 在“cellForRowAt”函数中,如果我这样做 "let text = arrayTexts[indexPath.section][indexPath.row]",出现错误'Type NSAttributedString has no subscript members'。 我能做什么?

声明:var arrayTexts = [NSAttributedString]()

填充:

let html = json["data"][order]["informations"][textIndex]["text"].stringValue
                            let textHtml = html.unescapingFromHTML


                            do {
                                let str = try NSMutableAttributedString(data: textHtml.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
                                let fullRange : NSRange = NSMakeRange(0, str.length)
                                str.addAttributes([NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 17.0)!], range: fullRange )

                                self.arrayTexts.append(str)
                                self.tableView.reloadData()
                            } catch {
                                print(error)
                            }

【问题讨论】:

  • 展示你如何声明和填充arrayTexts
  • 声明:var arrayTexts = [NSAttributedString]()。每个项目都是来自数据库的字符串,我使用“try NSMutableAttributedString (data : , options : , documentAttributes : )”将其转换为属性字符串并附加到 arrayTexts
  • 您的语法假定数组(行)位于数组(部分)[[<Type>]]
  • @vadian 是的,我尝试不使用 [indexPath.section] 并显示正确数量的部分,但所有部分中的文本都相同

标签: ios swift


【解决方案1】:

问题是你的let text = arrayTexts[indexPath.section][indexPath.row] 只有在你有一个 NSAttributedStrings 数组 ([[NSAttributedString]]) 的数组时才能工作。所以arrayTexts[indexPath.section] 会返回一个NSAttributedString,所以尝试用[indexPath.row] 下标会失败。如果不查看更多代码,很难准确理解您要做什么,但从您的描述看来,您只需将代码更改为 let text = arrayTexts[indexPath.section],它就会为您提供所需的内容。

【讨论】:

    【解决方案2】:

    需要声明数据源数组

    var arrayTexts = [[NSAttributedString]]()
    

    并填充数组

    self.arrayTexts.append([str])
    

    这将为每个项目创建一个部分。

    【讨论】:

    • 非常感谢您的帮助!我使用了我得到的另一个答案,但是通过您的答案,我学会了在单元格中使用更好的数组。非常感谢!
    猜你喜欢
    • 2018-03-31
    • 2021-06-05
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多