How to show superscript for “®” registered symbol?

前端 未结 6 2322
时光说笑
时光说笑 2021-02-13 01:10

I\'ve a issue regarding showing registered symbol as superscript. I\'ve used unicode value \\u00AE, but it shows in same line. I\'d like to have it a bit top of remaining texts.

6条回答
  •  旧时难觅i
    2021-02-13 01:51

    For newcomers, here is a relatively flexible, swift 4 solution, inspired by Integrating Stuff's original answer. I wrote it as an extension on NSAttributedString - that just seems like the cleanest solution in my mind. In order to superscript the (R) symbol, just pass the string "®" into this method from wherever you are calling it.

    extension NSAttributedString {
    
        class func superscriptInstances(ofString stringToReplace: String, withOriginalFont originalFont: UIFont, fromString string: String) -> NSAttributedString {
            let attributedString = NSMutableAttributedString(string: string)
            let length = attributedString.length
            let fontName = originalFont.fontName
            let fontSize = originalFont.pointSize
            let newSize = fontSize / 1.5
            let baselineOffset = fontSize / 3.0
            let newFont = UIFont(name: fontName, size: newSize)!
            var range = NSMakeRange(0, length)
            while (range.location != NSNotFound) {
                let nsstring = attributedString.string as NSString
                range = nsstring.range(of: stringToReplace, options: NSString.CompareOptions(rawValue: 0), range: range)
                if(range.location != NSNotFound) {
                    attributedString.addAttributes([.font: newFont,.baselineOffset: baselineOffset], range: range)
                    range = NSMakeRange(range.location + range.length, length - (range.location + range.length))
                }
            }
            return attributedString
        }
    
    }
    

提交回复
热议问题