Search code examples
stringdoubleswift3nsattributedstringnsmutableattributedstring

Swift 3.0 convert Double() to NSMutableAttributedString


in advance thanks for help.

I am trying to make calculator application (for specific purposes) and I would like to know, if there exist a way how to convert Double() to NSMutableAttributedString. I need this for label output answer.

Reason of using NSMutableAttributedString is because I would like to have answer with subscripts and upper-scripts.

//example of my code
var a = Double(), b = Double(), c = Double()
a = Double(textField1.text!)
b = Double(textField2.text!)
c = a + b
let font:UIFont? = UIFont(name: "Courier", size:12)
let fontSuper:UIFont? = UIFont(name: "Courier", size:10)


//for x_1 (subscript for "1")
x1_t:NSMutableAttributedString = NSMutableAttributedString(string: "x1", attributes: [NSFontAttributeName:font!])
x1_t.setAttributes([NSFontAttributeName:fontSuper!,NSBaselineOffsetAttributeName:-4], range: NSRange(location:1,length:1))


var result = NSMutableAttributedText()
// what to do to get output for a label like "x_1 = String(c) m"

If there exist another way like append String() to NSAtributedString() - I am looking forward for answers.


Solution

  • 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:

    enter image description here