기본 콘텐츠로 건너뛰기

Xcode Log - Label / Attributed Text - Replace

        let mutableString:NSMutableString = (resultLabel.attributedText as! NSMutableAttributedString).mutableString
        mutableString.replaceOccurrencesOfString("@1", withString: "109", options: 
NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, mutableString.length))

결국 이 두 줄의 코드.

AS3 할때도 이런 경우가 있었는데 HTML 형식으로 formatting한 label을 다룰때 생각보다 간단하지 않았다.
물론 해결하고 나니 속 시원했었지만.


이게 다 저 @1 부분을 replace 하려고 시작한 일이었다.
조금 더 다양한 가능을 보려고 손을 좀 더 보았다.



Xcode 에서 이걸 직접 살펴보았다.

                                <attributedString key="attributedText">
                                    <fragment content="이거이 사람이 할 짓이 아닌가 봅니다.
"
>
                                        <attributes>
                                            <color key="NSColor" cocoaTouchSystemColor="darkTextColor"/>
                                            <font key="NSFont" size="17" name="AppleSDGothicNeo-Regular"/>
                                            <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
                                        </attributes>
                                    </fragment>
                                    <fragment content="진짜">
                                        <attributes>
                                            <color key="NSColor" red="1" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
                                            <font key="NSFont" size="24" name="AppleSDGothicNeo-Bold"/>
                                            <font key="NSOriginalFont" size="17" name="AppleSDGothicNeo-Bold"/>
                                            <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
                                        </attributes>
                                    </fragment>
                                    <fragment content=" 속이 상해서 참말로
"
>
                                        <attributes>
                                            <color key="NSColor" cocoaTouchSystemColor="darkTextColor"/>
                                            <font key="NSFont" size="17" name="AppleSDGothicNeo-Regular"/>
                                            <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
                                        </attributes>
                                    </fragment>
                                    <fragment content="@1%">
                                        <attributes>
                                            <color key="NSColor" cocoaTouchSystemColor="darkTextColor"/>
                                            <font key="NSFont" size="24" name="AppleSDGothicNeo-Regular"/>
                                            <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
                                        </attributes>
                                    </fragment>
                                    <fragment content=" 부분만 살짝 갈아끼워줍니다.">
                                        <attributes>
                                            <color key="NSColor" cocoaTouchSystemColor="darkTextColor"/>
                                            <font key="NSFont" size="17" name="AppleSDGothicNeo-Regular"/>
                                            <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
                                        </attributes>
                                    </fragment>
                                </attributedString>

보면 attributedString 아래에 fragment 단위로 누어져있고 그 아래 attributes 가 있고 그 안에 color/font/paragrapthStyle 등등이 있는 걸 볼 수 있다.

HTML DOM 을 만드는 것과 비슷하게 할 수 있지만 지금 당장 필요한 것은 본문을 손상하지 않고 내용만 바꾸고 싶은데 이걸 전체를 들었다가 다시 생성하는 건 너무 삽질이라고 생각.

debugger를 열고 attributedText를 관찰해보자

(lldb) print (resultLabel.attributedText)
(NSAttributedString?) $R10 = 0x00007fa99c8a2f90 {
  ObjectiveC.NSObject = {...}
}


이런게 있다.
Mutable!! 바꿀 수 있다는 소리다!

(lldb) po (resultLabel.attributedText as! NSMutableAttributedString).mutableString
이거이 사람이 할 짓이 아닌가 봅니다.
진짜 속이 상해서 참말로
@1%
부분만 살짝 갈아끼워줍니다.

오케이!
이거야 이거!
mutableString 이면 바꿀 수 있다.


mutableString 을 보니 NSMutableString 이다.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/index.html#//apple_ref/occ/instm/NSMutableString/replaceOccurrencesOfString:withString:options:range:

MutableString 이라면 이런게 있지!
replaceOccurrencesOfString!!

Declaration

SWIFT
func replaceOccurrencesOfString(_ target: String,
                     withString replacement: String,
                        options options: NSStringCompareOptions,
                          range searchRange: NSRange) -> Int
OBJECTIVE-C
- (NSUInteger)replaceOccurrencesOfString:(NSString *)target                              withString:(NSString *)replacement                                 options:(NSStringCompareOptions)opts                                   range:(NSRange)searchRange
바꿀 것은 target 에 주고 withString 에 변경할 문자열을 지정한다.
정확한 일치를 원하므로 NSStringCompareOptions.LiteralSearch 를 사용한다.

여기에 Range 가 좀 걸리는데
만들어주자.

Declaration

SWIFT
func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange
OBJECTIVE-C
NSRange NSMakeRange ( NSUInteger loc, NSUInteger len );

Return Value

An NSRange with location location and length length.

Availability

Available in OS X v10.0 and later.
0부터 mutableString의 길이까지 지정해주면 된다.

새로 만드는 걸 했다면 거대한 삽질을 할뻔.



댓글

이 블로그의 인기 게시물

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

저지연 오디오 생성 LLVC 사용기

https://github.com/KoeAI/LLVC 써봄 CUDA 11.8 버전 쓰고 있어 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 VC 없어서 설치 https://wikidocs.net/168848 참조 FAIRSEQ 관련 오류 https://github.com/facebookresearch/fairseq/issues/2908 pip install editdistance  설치 No CUDA runtime is found, using CUDA_HOME='C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' 오류 멀쩡하게 있는데 안됨. pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio==2.1.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118 다시 설치 set DISTUTILS_USE_SDK=1 이게 문젠가 설정하고 재도전 Using cached ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl (118 kB) Building wheels for collected packages: fairseq   Building wheel for fairseq (pyproject.toml) ... error   error: subprocess-exited-with-error   × Building wheel for fairseq (pyproject.toml) did not run successfully.   │ exit code: 1   ╰─> [1829 lines of output]       No CUDA runtime is found, usi...