表格视图单元格内的textview中的文本未格式化

时间:2015-08-31 11:40:37

标签: ios uitableview uitextview

我正在尝试构建一个表视图,其中每个单元格都包含带有格式化文本的UITextView。我把所有东西放在一起,表格视图由文本填充。问题是,当我在模拟器中测试它时,文本没有格式化。只有在刷新后才会进行格式化。

这里我粘贴在视图控制器下面,它调用tableview和文本(来自SQLite数据库),以及我用来在UITextView中插入文本并对其进行格式化的类。我试图强制容器的布局,但它不起作用。

视图控制器

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var myTable: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.myTable.estimatedRowHeight = 44.0
    self.myTable.rowHeight = UITableViewAutomaticDimension
}

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 200
}    

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("verseCell") as! VerseTextView
    let row : Int = indexPath.row
    var getVerse = databaseDB()
    var verse = databaseVars()
    (verse.book, verse.chapter, verse.verseText) = getVerse.getVerseBy(row, database: databasePath as String)

    if verse.verseNumber == 1  {
        chapterToBePassed = String(verse.chapter)
    }
    else {
        chapterToBePassed = ""
    }
    cell.configure(verseChapter: chapterToBePassed, verseText: "\(verse.verseText)")
    return cell
}
}

VerseTextView类

class VerseTextView: UITableViewCell {

@IBOutlet weak var verse: UITextView!

func configure(#verseChapter: String?, verseText: String?) {

// Formats
        var style = NSMutableParagraphStyle()
        style.lineSpacing = 15
        let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
        let textFont = [NSFontAttributeName:font, NSParagraphStyleAttributeName : style]
        let fontChapter = UIFont(name: "Georgia-Bold", size: 22.0) ?? UIFont.systemFontOfSize(22.0)
        let chapterFont = [NSFontAttributeName:fontChapter]
        let myText = NSMutableAttributedString()
        var versettoId : String = ""

        if verseChapter != ""{
            let myTextChapter = "\n"+verseChapter!+"  "
            let capitolo = NSAttributedString(string: myTextChapter, attributes:chapterFont)
            myText.appendAttributedString(capitolo)
        }

        let testoVerso = verseText!+" "
        let verso = NSAttributedString(string: testoVerso, attributes:textFont)
        myText.appendAttributedString(verso)
        verse.attributedText = myText
//        verse.layoutManager.ensureLayoutForTextContainer(verse.textContainer)
//        verse.layoutIfNeeded()


    }
}

谢谢, 小号

1 个答案:

答案 0 :(得分:0)

试试这个,

cellForRowAtIndexpath

中的

let cell = tableView.dequeueReusableCellWithIdentifier("verseCell") as? VerseTextView

    if cell == nil {
         VerseTextView(style: .Default, reuseIdentifier: "verseCell")
    }

并实施VerseTextView(style: Style, reuseIdentifier: ReuseIdentifire)

在自定义单元格类