2014-10-09 84 views
51

我想使用NSLocalizedString本地化我的應用程序。當我導入XLIFF文件時,大部分工作就像一個魅力,但一些不這樣做,一些字符串未本地化。我已經注意到這個問題是從NSLocalizedString含有一些變量中,如:NSLocalizedString與swift變量

NSLocalizedString(" - \(count) Notifica", comment: "sottotitolo prescrizione per le notifiche al singolare") 

NSLocalizedString("Notifica per \(medicina!) della prescrizione \(prescription!)\nMemo: \(memoTextView.text)", comment: "Messaggio della Local Notification") 

也許這不是THI樣的東西正確的語法。有人可以解釋我如何迅速做到這一點?非常感謝你。

回答

84

您可以在NSLocalizedString使用sprintf格式參數,所以你的例子可以是這樣的:

let myString = String(format: NSLocalizedString(" - %d Notifica", comment: "sottotitolo prescrizione per le notifiche al singolare"), count) 
+4

它如何在Localizable.string – 2015-11-17 15:40:42

+0

中看起來與Obj-C相同:'「 - %d Notifica」=「 - %d Notifica」;' – ReDetection 2016-04-18 07:40:49

+0

如何替換字符串?我試圖使用'%s'修飾符,它無效= \ – igrek 2016-12-22 15:54:31

70

在活動#在WWDC2014 412的正確方法這雨燕「和Xcode 6本地化」以下:

String.localizedStringWithFormat(
    NSLocalizedString(" - %d Notifica", 
    comment: "sottotitolo prescrizione per le notifiche al singolare"), 
    count) 
+0

爲什麼你需要使用NSLocalizedString(...)?這不是在String.localizedStringWithFormat(...)的實現中發生的嗎? – Yitzchak 2016-09-27 05:27:38

+1

檢查出(http://stackoverflow.com/questions/26237549/how-does-localizedstringwithformat-work) – Mark 2016-09-27 12:40:56

+0

謝謝,我已經看到它後,我問。這對其他人非常有用,所以非常感謝 – Yitzchak 2016-09-27 12:56:43

-4

我創建了一個extensionString,因爲我有很多stringslocalized

extension String { 
    var localized: String { 
     return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") 
    } 
} 

例如:

let myValue = 10 
let anotherValue = "another value" 

let localizedStr = "This string is localized: \(myValue) \(anotherValue)".localized 
print(localizedStr) 
+4

這種方法的一個很大的缺點是,你必須手動提取字符串發送給翻譯器,因爲「編輯器>導出本地化...」不會選擇它們。 – 2017-01-23 17:29:26

+0

鑑於@JasonMoore的建議,我不認爲這是正確的做法。 – 2017-02-13 20:20:22

+0

@JasonMoore完全同意你的觀點。你們有沒有找到解決方案? – gasparuff 2017-04-12 19:39:23

10

我按照創建擴展到字符串的方法,因爲我有很多的字符串進行本地化。

extension String { 
    var localized: String { 
     return NSLocalizedString(self, comment:"") 
    } 
} 

在代碼中使用它的本地化做的事:

self.descriptionView.text = "Description".localized 

對於動態變量字符串如下:

self.entryTimeLabel.text = "\("Doors-open-at".localized) \(event.eventStartTime)" 

中聲明爲不同的語言(例如字符串文件中的字符串:阿拉伯語和英文)

enter image description here enter image description here

希望能幫助!