programing

Swift에서 NSLocalizedString에 해당하는 것은 무엇입니까?

elecom 2023. 5. 3. 20:49
반응형

Swift에서 NSLocalizedString에 해당하는 것은 무엇입니까?

스위프트에 해당하는 것이 있습니까?NSLocalizedString(...)Objective-C일반적으로 다음을 사용합니다.

NSString *string = NSLocalizedString(@"key", @"comment");

스위프트에서 동일한 작업을 수행하려면 어떻게 해야 합니까?함수를 찾았습니다.

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

하지만, 그것은 매우 길고 전혀 편리하지 않습니다.

다음 솔루션을 사용합니다.

확장명 만들기:

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

Localizable.strings 파일:

"Hi" = "Привет";

사용 예:

myLabel.text = "Hi".localized

즐기세요! ;)

--filename:--

설명이 있는 경우 이 솔루션을 사용할 수 있습니다.

확장:

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

.vmx 파일:

/* with !!! */
"Hi" = "Привет!!!";

사용:

myLabel.text = "Hi".localized(withComment: "with !!!")

NSLocalizedString스위프트의 세계에도 존재합니다.

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

tableName,bundle,그리고.value매개 변수는 키워드로 표시되므로 함수를 호출하는 동안 매개 변수를 생략할 수 있습니다.이 경우 기본값이 사용됩니다.

이는 메소드 호출을 다음과 같이 단순화할 수 있다는 결론으로 이어집니다.

NSLocalizedString("key", comment: "comment")

스위프트 5 - 변화가 없고, 여전히 그렇게 작동합니다.

기존 답변의 변형:

Swift 5.1:

extension String {

    func localized(withComment comment: String? = nil) -> String {
        return NSLocalizedString(self, comment: comment ?? "")
    }

}

그런 다음 코멘트 없이 간단히 사용할 수 있습니다.

"Goodbye".localized()
"Hello".localized(withComment: "Simple greeting")

참고로genstrings이 솔루션에서는 작동하지 않습니다.

이 방법을 사용하면 다른 유형(예: 통화 단위와 같은 사용자 정의 클래스)에 대해 다른 구현을 만들 수 있습니다.genstrings 유틸리티를 사용하여 이 메서드를 검색하여 호출할 수도 있습니다.명령에 루틴 플래그를 추가하기만 하면 됩니다.

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

확장명:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

용도:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

"댓글"이 항상 무시되는 사례에 대한 작은 도우미 메소드를 만들었습니다.코드 수가 적을수록 읽기 쉽습니다.

public func NSLocalizedString(key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

클래스 밖의 아무 곳에나 두면 Xcode가 이 글로벌 방법을 찾을 수 있습니다.

스위프트 3 버전 :)...

import Foundation

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

실제로 Swift 프로젝트에서 텍스트를 번역하기 위해 두 단계를 사용할 수 있습니다.

첫 번째 단계는 이전 방법을 사용하여 모든 변환 가능한 문자열을 만드는 것입니다.

NSLocalisedString("Text to translate", comment: "Comment to comment")

1.1) 그런 다음 genstring을 사용하여 Localizable.string을 생성해야 합니다.

$ genstrings *swift

나중에 이 대답을 사용해야 합니다.

2.1) 정규식에 따라 XCode "찾기 및 바꾸기" 옵션 사용주어진 예(댓글이 없는 경우)에 대해 정규식은 다음과 같습니다.

NSLocalizedString\((.*)\, comment:\ \"\"\) 

그리고 그것을 대체합니다.

$1.localized

또는 (댓글이 있는 경우)

NSLocalizedString\((.*)\, comment:\ (.*)\)

그리고 그것을 대체합니다.

$1.localizedWithComment(comment: $2)

정규식과 다른 확장 조합을 원하는 대로 자유롭게 사용할 수 있습니다.일반적인 방법은 전체 프로세스를 두 단계로 나누는 것입니다.도움이 되길 바랍니다.

아마도 가장 좋은 방법은 여기에 있는 이것일 것입니다.

fileprivate func NSLocalizedString(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

그리고.

import Foundation
extension String {
    static let Hello = NSLocalizedString("Hello")
    static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
    static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}

그러면 이렇게 사용할 수 있습니다.

let message: String = .ThisApplicationIsCreated
print(message)

나에게 이것은 최고입니다 왜냐하면

  • 하드코딩된 문자열은 하나의 특정 파일에 있으므로 변경하려는 날짜는 매우 쉽습니다.
  • 매번 파일에 문자열을 수동으로 입력하는 것보다 사용하기 쉽습니다.
  • 젠스트링은 계속 작동합니다.
  • 보기 컨트롤러당 하나의 확장 기능을 추가하여 깔끔하게 유지할 수 있습니다.

이것은 ".localized" 접근 방식의 개선입니다.클래스 확장자를 추가하는 것으로 시작합니다. 이렇게 하면 프로그래밍 방식으로 설정한 문자열에 도움이 됩니다.

extension String {
    func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
        return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
    }
}

프로그래밍 방식으로 설정한 문자열에 대한 사용 예:

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

이제 Xcode의 스토리보드 변환 파일은 파일 관리자를 지저분하게 만들고 스토리보드 업데이트도 제대로 처리하지 못합니다.더 나은 방법은 새 기본 레이블 클래스를 만들어 모든 스토리보드 레이블에 할당하는 것입니다.

class BasicLabel: UILabel {
    //initWithFrame to init view from code
    override init(frame: CGRect) {
      super.init(frame: frame)
      setupView()
    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
      setupView()
    }

    //common func to init our view
    private func setupView() {
        let storyboardText = self.text
        text = storyboardText?.localized()
    }
}

이제 사용자가 스토리보드에 추가하고 기본값을 제공하는 모든 레이블이 자동으로 번역됩니다.

UIButton에서도 동일한 작업을 수행할 수 있습니다.

class BasicBtn: UIButton {
    //initWithFrame to init view from code
    override init(frame: CGRect) {
      super.init(frame: frame)
      setupView()
    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
      setupView()
    }

    //common func to init our view
    private func setupView() {
        let storyboardText = self.titleLabel?.text
        let lclTxt = storyboardText?.localized()
        setTitle(lclTxt, for: .normal)
    }
}

SDK를 개발하는 경우.추가 수술이 필요합니다.

YourLocalizeDemoSDK에서 평소와 같이 Localizable.strings를 생성합니다.

로컬라이즈 데모에서 동일한 Localizable.string을 생성합니다.

LocalizeDemoSDK의 번들 경로를 찾습니다.

Swift4:

// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")

Bundle(for: type(of: self))YorLocalizeDemoSDK에서 수 .사용하는 경우Bundle.main대신 잘못된 값을 얻을 수 있습니다(실제로 키와 동일한 문자열이 됩니다).

그러나 만약 당신이 dr OX에서 언급한 String 확장자를 사용하고 싶다면,당신은 좀 더 해야 합니다.오리진 확장자는 다음과 같습니다.

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

SDK인하고 있습니다.Bundle.main. 그것은 우리가 원하는 것이 아닙니다.당신의 로컬라이즈 데모SDK에 번들이 필요합니다.이것은 그것을 빨리 찾기 위한 속임수입니다.

아래 코드를 YourLocalizeDemoSDK의 NSObject 인스턴스에서 실행합니다.그리고 YourLocalizeDemoSDK의 URL을 얻을 수 있습니다.

let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL

두 URL을 모두 인쇄하면 번들을 빌드할 수 있습니다.mainBundleURL 기반 SDK의 URL입니다.이 경우 다음과 같습니다.

let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main

String 확장자는 다음과 같습니다.

extension String {
    var localized: String {
        let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
    }
}

도움이 되길 바랍니다.

사용자 지정 번역 기능을 사용하여 문자열을 추출하는 일종의 자체 젠스트링 도구를 만들었습니다.

extension String {

    func localizedWith(comment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment)
    }

}

https://gist.github.com/Maxdw/e9e89af731ae6c6b8d85f5fa60ba848c

모든 스위프트 파일을 구문 분석하고 코드의 문자열과 주석을 .strings 파일로 내보냅니다.

아마도 그것을 하는 가장 쉬운 방법은 아닐 것이지만, 그것은 가능합니다.

이것이 단축 문제에 대한 답은 아니지만 메시지를 정리하는 데 도움이 되었지만 아래와 같은 오류 메시지에 대한 구조를 만들었습니다.

struct Constants {
    // Error Messages
    struct ErrorMessages {
        static let unKnownError = NSLocalizedString("Unknown Error", comment: "Unknown Error Occured")
        static let downloadError = NSLocalizedString("Error in Download", comment: "Error in Download")
    }
}

let error = Constants.ErrorMessages.unKnownError

이렇게 하면 메시지를 구성하고 젠트링이 작동하도록 할 수 있습니다.

그리고 이것은 사용된 genstrings 명령입니다.

find ./ -name \*.swift -print0 | xargs -0 genstrings -o .en.lproj

단위 테스트에서 사용할 수 있도록 도움말 가득 참:

이 버전은 다양한 사용 사례(예: tableNames 사용)로 확장할 수 있는 간단한 버전입니다.

public func NSLocalizedString(key: String, referenceClass: AnyClass, comment: String = "") -> String 
{
    let bundle = NSBundle(forClass: referenceClass)
    return NSLocalizedString(key, tableName:nil, bundle: bundle, comment: comment)
}

다음과 같이 사용합니다.

NSLocalizedString("YOUR-KEY", referenceClass: self)

아니면 이렇게 댓글 달면 됩니다.

NSLocalizedString("YOUR-KEY", referenceClass: self, comment: "usage description")

기본 언어를 사용한 현지화:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

예를 들어, 한 구절이 같은 영어에서 (성별, 동사 활용 또는 변화 때문에) 다른 언어로 번역할 때 스위프트에서 모든 경우에 작동하는 가장 간단한 NSS 문자열 형태는 세 가지 인수 1입니다.예를 들어, 영어 구절 "previous was"는 러시아어로 "체중"(прдбйлыищудпбаыыл)과 "허리"(редыдяащуе"п"▁("▁"баwaist"▁forыл)▁for▁the,)의 경우 다르게 번역됩니다.

이 경우 하나의 소스에 대해 두 가지 다른 번역이 필요합니다(WWDC 2018에서 권장되는 XLIFF 도구 측면).두 개의 인수 NSLocalizedString을 사용하여 이를 수행할 수 없습니다. 여기서 "이전"은 "키"와 영어 번역(즉, 값) 모두에 대해 동일합니다.유일한 방법은 세 개의 인수 형식을 사용하는 것입니다.

NSLocalizedString("previousWasFeminine", value: "previous was", comment: "previousWasFeminine")

NSLocalizedString("previousWasMasculine", value: "previous was", comment: "previousWasMasculine")

여기서 키("이전의 WasFeminine" 및 "이전의 WasMasculine")는 서로 다릅니다.

저는 일반적인 조언이 그 문구를 전체적으로 번역하는 것이라는 것을 알고 있지만, 때로는 너무 시간이 많이 걸리고 불편합니다.

확장명:

 extension String {
    func localized(comment: String = "") -> String {
        return NSLocalizedString(self, comment: comment)
    }
  }

사용:"_YOUR_STRING_NAME_".localized()

오래된 것을 찾고 교체하는 것이 귀찮다면 여기에 쓰여진 훌륭한 확장자 외에도.NSLocalizedString당신은 Xcode에서 찾기 및 바꾸기를 열 수 있고 찾기 섹션에서 쓸 수 있습니다.NSLocalizedString\(\(".*"\), comment: ""\)그런 다음 교체 섹션에 기록해야 합니다.$1.localized모든 것을 바꾸기 위해NSLocalizedString와 함께"blabla".localized당신의 프로젝트에서.

언급URL : https://stackoverflow.com/questions/25081757/whats-nslocalizedstring-equivalent-in-swift

반응형