development

신속한 변수가있는 NSLocalizedString

big-blog 2020. 10. 25. 12:35
반응형

신속한 변수가있는 NSLocalizedString


NSLocalizedString을 사용하여 내 앱을 지역화하려고합니다. XLIFF 파일을 가져올 때 대부분은 매력처럼 작동하지만 무언가가 그렇지 않고 일부 문자열이 현지화되지 않았습니다. 나는 문제가 다음과 같은 변수를 포함하는 NSLocalizedString에서 온 것으로 나타났습니다.

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

아마도 이것은 이러한 종류의 항목에 대한 올바른 구문이 아닐 수 있습니다. 누군가가 신속하게 수행하는 방법을 설명 할 수 있습니까? 대단히 감사합니다.


에서 sprintf형식 매개 변수를 사용할 수 NSLocalizedString있으므로 예제는 다음과 같습니다.

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

WWDC2014 "Localizing with Xcode 6"세션 # 412에서 Swift에서이를 수행하는 올바른 방법은 다음과 같습니다.

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

지역화 할 문자열이 많기 때문에 String 확장을 만드는 방법을 따랐습니다.

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

코드의 지역화에 사용하려면 다음을 수행하십시오.

self.descriptionView.text = "Description".localized

동적 변수가있는 문자열의 경우 다음을 따릅니다.

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

다른 언어에 대한 문자열 파일의 문자열 선언 (예 : 아랍어 및 영어)

여기에 이미지 설명 입력 여기에 이미지 설명 입력

희망이 도움이 될 것입니다!


다음은 String에서 사용하는 확장이며 변수 인수가있는 localizeWithFormat 함수를 추가합니다.

extension String:{

     func localizeWithFormat(arguments: CVarArg...) -> String{
        return String(format: self.localized, arguments: arguments)        
     }

     var localized: String{
         return Bundle.main.localizedString(forKey: self, value: nil, table: "StandardLocalizations")
     }
}

용법:

let siriCalendarText = "AnyCalendar"
let localizedText = "LTo use Siri with my app, please set %@ as the default list on your device reminders settings".localizeWithFormat(arguments: siriCalendarTitle)

String과 동일한 함수 및 속성 이름을 사용하지 않도록주의하십시오. 저는 일반적으로 모든 프레임 워크 기능에 3 자 접두사를 사용합니다.


위의 솔루션을 시도했지만 아래 코드가 저에게 효과적이었습니다.

SWIFT 4

extension String {

    /// Fetches a localized String
    ///
    /// - Returns: return value(String) for key
    public func localized() -> String {
        let path = Bundle.main.path(forResource: "en", ofType: "lproj")
        let bundle = Bundle(path: path!)
        return (bundle?.localizedString(forKey: self, value: nil, table: nil))!
    }


    /// Fetches a localised String Arguments
    ///
    /// - Parameter arguments: parameters to be added in a string
    /// - Returns: localized string
    public func localized(with arguments: [CVarArg]) -> String {
        return String(format: self.localized(), locale: nil, arguments: arguments)
    }

}

// variable in a class
 let tcAndPPMessage = "By_signing_up_or_logging_in,_you_agree_to_our"
                                     .localized(with: [tAndc, pp, signin])

// Localization File String
"By_signing_up_or_logging_in,_you_agree_to_our" = "By signing up or logging in, you agree to our \"%@\" and \"%@\" \nAlready have an Account? \"%@\"";

해야 할 일 이 많았 기 때문에 extensionto를 만들었습니다 .Stringstringslocalized

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)

참고 URL : https://stackoverflow.com/questions/26277626/nslocalizedstring-with-swift-variable

반응형