如何在UITextView中增加特定子字符串的字体大小?

时间:2019-04-04 17:00:19

标签: swift uitextview

我正在使用Swift 4.2构建的iPhone应用程序中尝试使用这种表示法

https://imgur.com/wCGfxrc

当前,我正在将表示形式创建为图像,并将其显示在UIImageView中。但是,与使用图像相比,我想增加代码中特定子字符串的大小。我不介意使用框架。

我尝试使用NSAttributedString,但是为每个字符串(有12个以上这样的字符串)定义它是一个繁琐的过程

编辑:

因此,我在 Swift 4.2,iOS 12 中创建了以下类:

public class representations {

func plus1() -> [NSAttributedString.Key: Any]{
    let plus1: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 30)
    ]
    return plus1
}

func plus2() -> [NSAttributedString.Key: Any]{
    let plus1: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 33)
    ]
    return plus1
}

func minus1() -> [NSAttributedString.Key: Any]{
    let minus1: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 18)
    ]
    return minus1
}

func minus2() -> [NSAttributedString.Key: Any]{
    let minus2: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 16)
    ]
    return minus2
}

func boldify() -> [NSAttributedString.Key: Any]{
    let bold: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 20)
    ]
    return bold
}

func correct() -> [NSAttributedString.Key: Any]{
    let correct: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.green
    ]
    return correct
}

func incorrect() -> [NSAttributedString.Key: Any]{
    let incorrect: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.red
    ]
    return incorrect
}


}

以下是函数调用的工作方式:

for (innerKey,innerValue) in value["attributes"] as! [String: [String: [Int]]]{
    var i = 0
    let loc = innerValue["location"] as! [Int]
    let length = innerValue["length"] as! [Int]
    for location in loc {
    switch(innerKey){
         case "plus1" :
                    attributedString.addAttributes(rep.plus1(), range: NSRange(location: location-1, length: length[i]))
         case "plus2" :
                    attributedString.addAttributes(rep.plus2(), range: NSRange(location: location-1, length: length[i]))
         case "minus1" :
                    attributedString.addAttributes(rep.minus1(), range: NSRange(location: location-1, length: length[i]))
         case "minus2" :
                    attributedString.addAttributes(rep.minus2(), range: NSRange(location: location-1, length: length[i]))
         default:
                    print("default case")
        }
        i+=1

    }
}

将属性添加到何处的所有数据都存储在字典中

        "attributes" : [
            "plus1" : [
                "location" : [32,34],
                "length" : [1,3]
            ],
            "plus2" : [
                "location" : [33],
                "length" : [1]
            ],
        ]

这是result

1 个答案:

答案 0 :(得分:1)

NSAttributedString实际上是您唯一的选择,因为此格式可以包含多种文本格式。您可以编写一个脚本来“扫描”普通文本中的某些单词,然后为每个字符升级字体+1大小,直到达到中间,然后再次减小字体,直到再次达到默认字体。