具有不同格式的 Swift UITextView

标签 swift uitextview

很抱歉问了一个基本问题,但我不知道从哪里开始。在 Swift 中可以执行以下操作吗?

In a UITextView (Not a label, as in the possible duplicate), different bits of text having different formatting: for instance, a line of large text in the same UITextView as a line of small text. Here is a mockup of what I mean: enter image description here

这可以在一个 UITextView 中实现吗?

最佳答案

你应该看看NSAttributedString。以下是如何使用它的示例:

    let largeTextString = "Here is some large, bold text"
    let smallTextString = "Here is some smaller text"

    let textString = "\n\(largeTextString)\n\n\(smallTextString)"
    let attrText = NSMutableAttributedString(string: textString)

    let largeFont = UIFont(name: "Arial-BoldMT", size: 50.0)!
    let smallFont = UIFont(name: "Arial", size: 30.0)!

    //  Convert textString to NSString because attrText.addAttribute takes an NSRange.
    let largeTextRange = (textString as NSString).range(of: largeTextString)
    let smallTextRange = (textString as NSString).range(of: smallTextString)

    attrText.addAttribute(NSFontAttributeName, value: largeFont, range: largeTextRange)
    attrText.addAttribute(NSFontAttributeName, value: smallFont, range: smallTextRange)

    textView.attributedText = attrText

结果:

enter image description here

关于具有不同格式的 Swift UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29639598/

相关文章:

Swift 3 不正确的字符串插值与隐式展开的 Optionals

objective-c - 无法将类型的值转换为预期的参数类型

ios - Storyboard中 UITextView 的本地化

iphone - 在文本字段上崩溃单击 iOS 6.0 和 xcode 4.5

iphone - 如何使用返回键关闭 UITextView 的键盘?

ios - UITextView滚动时 float 蓝框

swift - Firebase 基于孙值写入 (Swift)

ios - SWIFT:如何使用不同类的performSegueWithIdentifier

Swift:异步方法进入 while 循环

ios - iOS 的 Twitter UITableViewCell 链接检测(Swift)