Swift 3.0 convert Double() to NSMutableAttributedString

江枫思渺然 提交于 2019-12-06 17:47:27

As I understand it, your input strings (named "prestring1" and "afterstring1" in your own answer) could just be normal strings without attributes, because you only need the final result to be an attributed string.

This would drastically simplify your function, for example you could use string interpolation first and then only make an attributed string and move up (or down) the last part (or any part you want, I'm using an hardcoded range in my example but it's just an example).

Like:

let randomstring = "Random ="
let afterstring = "m2"
let result: Double = 42.1

func stringer (pre: String,
               result: Double,
               post: String) -> NSMutableAttributedString
{
    let base = "\(pre) \(result) \(post)"
    let mutable = NSMutableAttributedString(string: base)
    mutable.addAttribute(NSBaselineOffsetAttributeName, value: 4,
                         range: NSRange(location: mutable.length - 2, length: 2))
    return mutable
}

let attributedString = stringer(pre: randomstring, result: result, post: afterstring)

Gives:

I am still not quit sure how to do it, but I could create simple function, which is approximately doing what I need. Here I am sharing my answer in case someone has the same question, but in case someone knows better answer, share it with others :)

var randomstring = "Random ="

var prestring1 = NSMutableAttributedString(string: randomstring)
var afterstring1 = NSMutableAttributedString(string: "m2")
var result1 = Double()
result1 = 42.1

func stringer (prestring: NSMutableAttributedString, result: Double, afterstring: NSMutableAttributedString) -> NSMutableAttributedString {
var mutableatributedresult = NSMutableAttributedString(string: String(result))
var mutableaddition = NSMutableAttributedString(string: " ")
var alltext = NSMutableAttributedString()

alltext.append(prestring)
alltext.append(mutableaddition)
alltext.append(mutableatributedresult)
alltext.append(mutableaddition)
alltext.append(afterstring)

return alltext
}

stringer(prestring: prestring1, result: result1, afterstring: afterstring1)

//This should give result of "Random = 42.1 m2"

If someone knows better solution I am curious.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!