1

感謝您的幫助。Swift 3.0提前將Double()轉換爲NSMutableAttributedString

我試圖讓計算器應用(用於特定目的),我想知道,如果存在的方式如何雙()轉換爲NSMutableAttributedString。我需要這個標籤輸出答案。

使用NSMutableAttributedString的原因是因爲我想有與標和上腳本的答案。

//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" 

如果存在另一種方式像追加String()到NSAtributedString() - 我期待着答案。

回答

0

據我瞭解,您輸入的字符串(命名爲自己的回答「prestring1」和「afterstring1」)可能只是不屬於正常的字符串,因爲你只需要最後的結果是一個屬性串。

這將大大簡化您的功能,例如,您可以先使用字符串插值,然後只製作屬性字符串並向上(或向下)移動最後一部分(或任何您想要的部分,我使用硬編碼範圍在我的例子中,但它只是一個例子)。

像:

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) 

給出:

enter image description here

+0

當然,如果我誤解了,如果你確實需要'NSMutableAttributedString's作爲輸入,請發表評論,這樣我就可以更新..或刪除。 ;) – Moritz

+0

謝謝你的回覆!我很喜歡你的方式。事情是,有時我甚至需要把屬性字符串放在之前(比如V_Ed = 21 m^2; _下標,^上標)。除了「.append」之外,我找不到真正的教程。如何實際創建NSMutableAttributedString的結果以及後來的附加屬性比我的情況要好得多,因爲您可以稍後在文本的任何部分設置屬性的任何部分。你回答我的問題,再次感謝! –

0

我仍然沒有放棄知道怎麼做,但我可以創建簡單的功能,這大約是在做什麼,我需要。我在這裏分享我的答案,以防有人有同樣的問題,但如果有人知道更好的答案,分享與他人:)

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" 

如果有人知道更好的解決方案我很好奇。