Swift 3.0将Double()转换为NSMutableAttributedString [英] Swift 3.0 convert Double() to NSMutableAttributedString

查看:116
本文介绍了Swift 3.0将Double()转换为NSMutableAttributedString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提前感谢您的帮助。

我正在尝试制作计算器应用程序(为特定目的),我想知道,如果有一种方式如何将Double()转换为NSMutableAttributedString。我需要这个标签输出答案。

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.

使用NSMutableAttributedString的原因是因为我想用下标和高脚本来回答。

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"

如果存在另一种方式,例如向NSAtributedString()附加String() - 我期待着答案。

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

推荐答案

据了解,您的输入字符串(在您自己的答案中名为prestring1和afterstring1)可能只是正常的字符串,没有属性,因为您只需要最终结果成为一个归因的字符串。

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.

这将大大简化您的功能,例如,您可以先使用字符串插值,然后只做一个n归因字符串,并向上(或向下)最后一部分(或任何您想要的部分,我在我的示例中使用硬编码的范围,但这只是一个例子)。

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).

喜欢:

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)

提供:

这篇关于Swift 3.0将Double()转换为NSMutableAttributedString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆