ios - 换行符(\n)不能快速工作

标签 ios string swift

我正在使用 swift 开发我的第一个 iOS 应用程序。我需要在 UILabel 中使用换行符 (\n) 显示一些细节。当我像下面这样直接分配时它工作得很好

myLabel.text = "\nSome \n\n Text here\n"

因为我需要存储文本,所以我将其存储为核心数据并以字符串形式检索。

let context: NSManagedObjectContext = appDel.managedObjectContext


    let fetchRequest = NSFetchRequest()

    let entityDescription = NSEntityDescription.entityForName("Details", inManagedObjectContext: context)

    fetchRequest.entity = entityDescription

    do {
        let result = try context.executeFetchRequest(fetchRequest)
        print(result.count)
        if (result.count > 0) {
            for i in 0..<result.count
            {
                let person = result[i] as! NSManagedObject

                fee = person.valueForKey("fee") as! String
                content = person.valueForKey("content") as! String
                pattern = person.valueForKey("pattern") as! String
                documentation = person.valueForKey("documentation") as! String

            }
        }

    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

但是当我将费用设置为标签文本时,换行不起作用。

myLabel.text = fee

我该怎么做才能做到这一点?
提前致谢。

最佳答案

当您使用 coredata 或 sqlite 在本地数据库中保存带有 \n 的文本时。 它会自动另外设置另一个反斜杠。 因此,当您获取字符串并尝试打印它时,它只会显示您保存它的方式。 只需使用此行即可在标签中显示多行文本。

swift 2.0

    let fee = person.valueForKey("fee") as? String
    let newText = fee?.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
    myLabel.text = newText

swift 3.0

    guard let fee = person.valueForKey("fee") as? String else {return}
    let newText = fee.replacingOccurrences(of: "\\n", with: "\n")
    myLabel.text = newText

Don't forget to allow UILabel object to show infinite line by setting number of lines = 0

关于ios - 换行符(\n)不能快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053698/

相关文章:

c - 带空格的字符串连接

ios - Xcode 无法识别 GoogleAPIClientForREST?

ios - 为什么我不能在 Swift 中自己运行命令?

ios - 为什么整个单词的 sizeWithFont 不同于其字母大小的总和?

ios - 如何在 iOS 版 Google map 中添加自定义数据以叠加?

PHP:比较子字符串

python - 等效 Unicode 字符串的相等性

ios - 静音/静音模式打开时声音仍在播放

ios - animator.startAnimation -- 这个警告是什么意思?

ios - 在 iOS 中计算网络速度。数据较少的往返时间不会告知确切的网络速度