기본 콘텐츠로 건너뛰기

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를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

LG G Pro 2 Custom Rom +Rooting 기록

선 루팅 https://forum.xda-developers.com/lg-g3/general/guide-root-lg-firmwares-kitkat-lollipop-t3056951 1.2버전 스크립트 모드로. echo Looking for LG serial port.. echo. adb.exe wait-for-device 여기에서 정체 상태여서 강제로 adb kill-server 했더니 알아서 재부팅하심. 폰에선 "펌웨어 업데이트"화면이 나오고 Phone found at COM5! Rooting phone.. If you don't see the SuperSu installer script runs within about a minute, then the root failed. Author : blog.lvu.kr SPECIAL COMMAND : ENTER, LEAVE ## 이런 상황이 됨. #이 느린 속도로 하나씩 증가하고 있음. 한 시간 기다려도 성과없음. 뭐 몇번해봐도 안되고 결국 불안하긴 하지만 kingroot.net  로 설치 롤리팝이니까  https://drive.google.com/file/d/0B4kfGU1z_PClQ3AyM2lKOGR1S3M/view  이걸 받아서 압축 풀기. d838recovery.bat 만 있어서 당황스럽긴한데 실행하고 1번 하니까 리커버리 모드 진입까진 잘 되는 듯. adb sideload 라는게 있어서 해봄. Advance에서 adb sideload 선택하고 USB연결한 PC에서 adb sideload RR-N-v5.8.5-20171010-d838-Final.zip 하니까 착착 잘 진행됨. 이제 흉측한 U+LTE 가 없어짐. ㅇㅋ 군더더기 없고 깔끔한데 남은 건 gapps 를 설치해야함. http://opengapps.org/  를 권해줘서 갔는데 지옥 느림. ARM + 7.1 + stock 이 기본이...

Google Daydream 소감

드디어 V30 사은품인 Daydream이 왔다. 낭랑한 벨과 함께 무심한 듯 시크하게 툭 던지고 가시는 택배느님. 수령까지 두달 걸렸다. 눈을 뜨고 꿈꿔 보세요. 여기가 눈감으면 코베어 간다는 서울인가? 주황색면으로 열면 된다. 컨트롤러의 만듦새는 아주 좋다. 기존에 나와있는 사진엔 가로 머리끈만 있어서 똥머리한 언니들도 막 쓰고 플레이하고 그랬는데 실제로 보니 이중 끈이었다. 보통 돌아다니는 착샷 Daydream 설치 - 실행 - 폰 장착 - 컨트롤러 페어링 - VR진입까지 과정을 쉽게 하려고한 노력이 보였음. NFC로 데이드림뷰어에 폰을 장착하면 자동으로 인식하여 데이드림 앱이 실행되는 경험은 꽤 괜찮았음. 컨트롤러는 크기, 그립감 면에서 매우 훌륭하고 인식률, 반응속도 모두 만족스러움. 홈버튼으로 시선을 재 조정하는 발상은 좋은데 왼쪽 오른쪽이 앱마다 조금 혼란스럽고 상하방향 캘리브레이션은 안된다. 이 부분에서 좌절했다. 누워서 넷플릭스를 보는 건 다른 방법을 찾아보아야한다는 소리. 알고보니 이런 건 Youtube이나 Netflix, Skybox player 등등에서 테스트해본 결과 자체 앱에서 지원하고 있다. Netflix는 void theater라는 것이 있는데  <출처:  https://元ボクサーの一念発起.com/2018/05/10/oculus-go/ > Netflix app에서 요렇게 눈송이 같이 생긴 아이콘을 컨트롤러로 찍고 들어가면 화면만 덩그러니 나오고 스티어링휠(자동차 핸들) 모양 아이콘을 선택하고 누으면 자연스럽게 조정이 되었다. Youtube나 Skybox앱의 경우 아예 컨트롤러에서 꾹 누르고 화면 이동하는게 가능해서 편리. 게임은 이것저것 해봤는데 Rez Infinite이 최고. 아니 이건 그냥 전 VR 기기를 통틀어서 Rez Infinite이 최고가 아닐까 싶음;;; 결론,  1. 누워서 보기 잘된다. 2. ...