반응형

Type 1

  • The way to do it is to use NSAttributedString like this:

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 1)];

[label setAttributedText: text];

 

 

 

Type 2

  • First of all initialize of you NSString and NSMutableAttributedString as below.

var myString:NSString = "I AM KIRIT MODI"

var myMutableString = NSMutableAttributedString()

 

In ViewDidLoad

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])

    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

    // set label Attribute

    labName.attributedText = myMutableString

    super.viewDidLoad()

}

 

 

  • MULTIPLE COLOR

Add the line code below in your ViewDidLoad to get multiple colors in a string.

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])

myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

 

 

 

 

Type 3

  • By using following extension function, you can directly set a color attribute to an attributed string and apply the same on your label.

extension NSMutableAttributedString {

    func setColorForText(textForAttribute: String, withColor color: UIColor) {

        let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)

 

        // Swift 4.2 and above

        self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)

 

        // Swift 4.1 and below

        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)

    }

}

 

 

  • Try above extension, using a label:

let label = UILabel()

label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)

let stringValue = "stackoverflow"

 

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)

attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)

attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)

attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)

label.font = UIFont.boldSystemFont(ofSize: 40)

 

label.attributedText = attributedString

self.view.addSubview(label)

 

 

 

 

Type 4

  • You can easily use html inside attributedText property of the UILabel to easily do various text formatting.

    let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"

    let encodedData = htmlString.data(using: String.Encoding.utf8)!

    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

    do {

        let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)

        label.attributedText = attributedString

    } catch _ {

        print("Cannot create attributed String")

    }

 

 

 

 

Type 5

  • In my case, I needed to be able to set different colors/fonts within labels frequently so I made a UILabel extension using Krunal's NSMutableAttributedString extension.

    func highlightWords(phrases: [String], withColor: UIColor?, withFont: UIFont?) {

    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)

    for phrase in phrases {

        if withColor != nil {

            attributedString.setColorForText(textForAttribute: phrase, withColor: withColor!)

        }

        if withFont != nil {

            attributedString.setFontForText(textForAttribute: phrase, withFont: withFont!)

        }

    }

    self.attributedText = attributedString

}

 

  • It can be used like this:

yourLabel.highlightWords(phrases: ["hello"], withColor: UIColor.blue, withFont: nil)

yourLabel.highlightWords(phrases: ["how are you"], withColor: UIColor.green, withFont: nil)

 

 

 

 

Type 6

  • Here is an extension for NSMutableAttributedString, that add/set color on string/text.

extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {

        let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)

        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)

    }

}

 

  • Now, try above extension with UILabel and see result

let label = UILabel()

label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)

let red = "red"

let blue = "blue"

let green = "green"

let stringValue = "\(red)\n\(blue)\n&\n\(green)"

label.textColor = UIColor.lightGray

label.numberOfLines = 0

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)

attributedString.setColor(color: UIColor.red, forText: red)   // or use direct value for text "red"

attributedString.setColor(color: UIColor.blue, forText: blue)   // or use direct value for text "blue"

attributedString.setColor(color: UIColor.green, forText: green)   // or use direct value for text "green"

label.font = UIFont.systemFont(ofSize: 26)

label.attributedText = attributedString

self.view.addSubview(label)

 

 

 

Type 7

  • HTML문자열 데이터를 특성 문자열 텍스트로 변환 

[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 

                                                                                                          options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)

} documentAttributes:nil error:nil];

 

 

  • using NSMutableAttributedString from html string 

NSHTMLTextDocumentTypeNSString *s = @"<p><a href='https://itunes.apple.com/us/app/xxxx/xxxx?mt=8'>https://itunes.apple.com/us/app/xxxx/xxxx?mt=8</a></p>";

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithData:[s dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ];

myUILabel.attributedText = text;

 

 

 

 

 

참고

  • HTML to NSAttributedString

 NSString *htmlString=[[NSString alloc]initWithFormat:@"<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"];

//Converting HTML string with UTF-8 encoding to NSAttributedString

 NSAttributedString *attributedString = [[NSAttributedString alloc]

                                        initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]

                                        options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }

                                        documentAttributes: nil

                                        error: nil ];

 

  • NSAttributedString to HTML

//Dictionary to hold all the attributes of NSAttributed String

 NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};

 //Saving the NSAttributedString with all its attributes as a NSData Entity

 NSData *htmlData = [attributedString dataFromRange:NSMakeRange(0, attributedString.length) documentAttributes:documentAttributes error:NULL];

 //Convert the NSData into HTML String with UTF-8 Encoding

 NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

 

 

출처 :

https://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label

 

 

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

Tcpdump 사용법  (0) 2020.05.19
APNs - 기능 및 유실 사례  (0) 2020.05.18
OpenSSL Mac 연동  (0) 2020.05.18
NSLog 출력 크기 제한 풀기  (0) 2020.05.18
탈옥후 안정화  (0) 2020.05.18
블로그 이미지

SKY STORY

,
반응형
반응형

'개발 > Note' 카테고리의 다른 글

Base64 encode / decode in C++  (0) 2020.05.29
HTTP Content-Type  (0) 2020.05.29
HMAC SHA256  (0) 2020.05.28
UUID의 구성 요소  (0) 2020.05.19
Release 모드에서 디버깅  (0) 2020.05.18
블로그 이미지

SKY STORY

,

OpenSSL Mac 연동

개발/iOS 2020. 5. 18. 11:15
반응형

SSL 접속 ssh root@192.168.0.112

[ 비밀번호 입력 ]

 

The authenticity of host '192.168.0.112 (192.168.0.112)' can't be established. RSA key fingerprint is SHA256:r0yomySgcGIUYEun3FJM4P0XpZ8CSFYJOxBU+p7UVB8.

Are you sure you want to continue connecting (yes/no)? yes 

Warning: Permanently added '192.168.0.112' (RSA) to the list of known hosts. 

root@192.168.0.112's password:

 

Cydia를 통해 OpenSSH 및 iFile설치 OpenSSH는 PC에서 디바이스에 원격으로 접속하기 위해 설치(PC에서 터미널을 사용하기 위 함) 

iFile : iOS는 Android와 같은 ADB환경이 구축되지 않아, PC와 iOS디바이스 간의 파일 전송이 필요함.

 

putty로 iOS 디바이스의 IP로 SSL접속 후 iOS용으로 빌드된 apt-get을 push해준다. 

cd /usr/bin/

 

/usr/bin/ 내의 apt-get에 실행 권한을 주고 Cydia에서 APT 0.7 Strict를 설치해주면 apt-get 명령을 사용할 수 있다.

chmod 755 apt-get

 

만약 /usr/bin/ 디렉토리에 gdb가 존재하지 않는다면 gdb를 설치해준다. 

sudo apt-get update 

sudo apt-get install gdb

 

gdb 실행 권한 설정 

chmod 755 gdb

 

원격 터미널로 접속하기 위해 App의 PID 정보 확인한다. 

grep명령으로 앱의 저장 경로 및 PID 정보를 출력한다. 

ps -ef | grep UBpayLibDev 

 

 

PID를 이용하여 gdb Attach한다. 

gdb -p 925

 

유틸 설치 

sudo apt-get install flex bison 

sudo apt-get install build-essential gcc-multilib lib32stdc++-5-dev 

python-dev python3-dev git

 

2020/05/18 - [iOS/Objective-C] - NSLog 출력 크기 제한 풀기

2020/05/18 - [OS/Mac OS X] - Symbolic Link

2020/05/18 - [개발툴/Xcode] - Release 모드에서 디버깅

2020/05/18 - [iOS/Jailbreak] - 탈옥후 안정화

2020/05/15 - [iOS/Swift] - 다중 문자열 / 캐릭터 제거

2020/05/15 - [iOS/Swift] - String substring

2020/05/15 - [iOS/Swift] - Framework 경로

2020/05/15 - [iOS/Objective-C] - Frameworks 경로

2020/05/15 - [iOS/Objective-C] - iOS디바이스 설정창 이동

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - json 포멧 체크

2020/05/12 - [iOS/Swift] - Access Control (접근 제한자)

2020/05/12 - [iOS/Swift] - WKWebview에서 tel, email, mailto, sms, facetime 처리

 

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

APNs - 기능 및 유실 사례  (0) 2020.05.18
Multiple font colors in a single UILabel  (0) 2020.05.18
NSLog 출력 크기 제한 풀기  (0) 2020.05.18
탈옥후 안정화  (0) 2020.05.18
다중 문자열 / 캐릭터 제거  (0) 2020.05.15
블로그 이미지

SKY STORY

,
반응형

NSLog의 최대 출력은 1024 byte까지만 출력이 가능하다.

만약 이 한계를 넘어서는 로그 출력시 일부분만 출력 되게 된다.

 

다음과 같이 printf C함수를 사용하여 매크로 함수 선언후 사용하면 1024 byte 이상 문자열을 출력할 수 있다.

#ifdef DEBUG 

#define NSLogEx FORMAT, ...) printf("%s(%d) : %s\n", __PRETTY_FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]); 

#else

#define NSLogEx( FORMAT, ... ) 

#endif

 

사용방법 

NSString *logString = @“Q@# …. @#$”; 

NSLogEx(@“%@“, logString);

 

2020/05/18 - [OS/Mac OS X] - Symbolic Link

2020/05/18 - [개발툴/Xcode] - Release 모드에서 디버깅

2020/05/18 - [iOS/Jailbreak] - 탈옥후 안정화

2020/05/15 - [iOS/Swift] - 다중 문자열 / 캐릭터 제거

2020/05/15 - [iOS/Swift] - String substring

2020/05/15 - [iOS/Swift] - Framework 경로

2020/05/15 - [iOS/Objective-C] - Frameworks 경로

2020/05/15 - [iOS/Objective-C] - iOS디바이스 설정창 이동

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - json 포멧 체크

2020/05/12 - [iOS/Swift] - Access Control (접근 제한자)

2020/05/12 - [iOS/Swift] - WKWebview에서 tel, email, mailto, sms, facetime 처리

 

반응형

'개발 > iOS' 카테고리의 다른 글

Multiple font colors in a single UILabel  (0) 2020.05.18
OpenSSL Mac 연동  (0) 2020.05.18
탈옥후 안정화  (0) 2020.05.18
다중 문자열 / 캐릭터 제거  (0) 2020.05.15
String substring  (0) 2020.05.15
블로그 이미지

SKY STORY

,

Symbolic Link

개발/Mac OS X 2020. 5. 18. 10:59
반응형

심볼릭 링크는 윈도우의 바로 가기와 비슷하고 하드 링크는 원래 파일 데이터의 또 다른 접근 경로 입니다.


심볼릭 링크 > 원본 파일 > 실제 파일 데이터 

하드 링크 > 실제 파일 데이터 < 원본 파일


심볼릭 링크, 하드 링크 만들기

1. 심볼릭 링크 생성

ln -s (원본 파일이나 폴더 경로) (심볼릭 링크가 저장될 경로)

ex) ln -s /Volumes/DATA/Users/jhrunning/Desktop/Folder /Volumes/DATA/Users/ jhrunning/Desktop/SymFolder


2. 하드 링크 생성

ln (원본 파일 경로) (하드 링크 파일이 저장될 경로)

ex) ln -s /Volumes/DATA/Users/jhrunning/Desktop/origin.txt /Volumes/DATA/Users/ jhrunning/Desktop/result.txt



< 사용 예 >

symbolic link (심볼링 링크 생성 ; 링크 폴더 생성) 

ln -s [패스1] [패스2] 패스1 폴더를 패스2폴더에 링크 (패스2는 패스1을 바라봄) 

// Dropbox sudo ln -s /Volumes/DATA/Dropbox ~/Dropbox 

// Google Drive sudo ln -s /Volumes/DATA/Google\ Drive ~/Google\ Drive 

// OneDrive sudo ln -s /Volumes/DATA/OneDrive ~/OneDrive 

// Music/iTunes sudo ln -s /Volumes/DATA/Music/iTunes /Users/netcanis/Music/iTunes

// Xcode sudo ln -s /Volumes/DATA/Xcode /Applications/Xcode

// MSOffice sudo ln -s /Volumes/DATA/MSOffice /Applications/MSOffice

// Pictures sudo ln -s /Volumes/DATA/Pictures ~/Pictures

// iTunes Backup 일부 폴더는 생성시 권한 에러로 생성이 불가능하다 

sudo ln -s /Volumes/TDRIVE/Backup ~/Library/Application\ Support/MobileSync/ Backup 

이런경우 아래와 같이 ~/ 쪽에 생성한후 해당디렉토리에 복사하도록 한다.

sudo ln -s /Volumes/TDRIVE/Backup ~/Backup


2020/05/18 - [개발툴/Xcode] - Release 모드에서 디버깅

2020/05/18 - [iOS/Jailbreak] - 탈옥후 안정화

2020/05/15 - [iOS/Swift] - 다중 문자열 / 캐릭터 제거

2020/05/15 - [iOS/Swift] - String substring

2020/05/15 - [iOS/Swift] - Framework 경로

2020/05/15 - [iOS/Objective-C] - Frameworks 경로

2020/05/15 - [iOS/Objective-C] - iOS디바이스 설정창 이동

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - json 포멧 체크

2020/05/12 - [iOS/Swift] - Access Control (접근 제한자)

2020/05/12 - [iOS/Swift] - WKWebview에서 tel, email, mailto, sms, facetime 처리


반응형

'개발 > Mac OS X' 카테고리의 다른 글

duplicate symbol 에러 해결  (0) 2020.06.16
iPhone SDK location on hard drive  (0) 2020.05.29
gdb 사용  (0) 2020.05.19
gdb 설치  (0) 2020.05.19
Mac에서 Node.js 설치  (0) 2020.05.19
블로그 이미지

SKY STORY

,
반응형

• Configurations에서 Release 설정 복사한 새로운 설정을 생성한다.

 

 

• 적절한 이름으로 설정해 준다. (ex. ‘Release Mode Debugging’)

 

 

• 프로비저닝 설정을 개발로 설정해 준다. 

 

 

• Edit Scheme를 클릭

 

 

• 빌드 설정을 ‘Release Mode Debugging’로 변경

 

 

• 로그는 출력되지 않지만 코드상에 브레이크 포인트로 디버깅이 가능하다.

 

 

2020/05/18 - [iOS/Jailbreak] - 탈옥후 안정화

2020/05/15 - [iOS/Swift] - 다중 문자열 / 캐릭터 제거

2020/05/15 - [iOS/Swift] - String substring

2020/05/15 - [iOS/Swift] - Framework 경로

2020/05/15 - [iOS/Objective-C] - Frameworks 경로

2020/05/15 - [iOS/Objective-C] - iOS디바이스 설정창 이동

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - json 포멧 체크

2020/05/12 - [iOS/Swift] - Access Control (접근 제한자)

2020/05/12 - [iOS/Swift] - WKWebview에서 tel, email, mailto, sms, facetime 처리

 

반응형

'개발 > Note' 카테고리의 다른 글

Base64 encode / decode in C++  (0) 2020.05.29
HTTP Content-Type  (0) 2020.05.29
HMAC SHA256  (0) 2020.05.28
UUID의 구성 요소  (0) 2020.05.19
Storyboard References (스토리보드 분리)  (0) 2020.05.18
블로그 이미지

SKY STORY

,

탈옥후 안정화

개발/iOS 2020. 5. 18. 10:31
반응형
반응형

'개발 > iOS' 카테고리의 다른 글

OpenSSL Mac 연동  (0) 2020.05.18
NSLog 출력 크기 제한 풀기  (0) 2020.05.18
다중 문자열 / 캐릭터 제거  (0) 2020.05.15
String substring  (0) 2020.05.15
Framework 경로  (0) 2020.05.15
블로그 이미지

SKY STORY

,
반응형

다중 캐릭터 제거

func removeAll(characters: [Character]) -> String {
    return String(self.filter({ !characters.contains($0) }))
}

[사용방법]

var retString = "2020-04-12 11:22:59"

let ret = retString.removeAll(characters: [" ", "-", ":"])

print("\(ret)")

20200412112259

 

 

다중 문자열 제거

func removeAll(strings: [String]) -> String {
    var retString = self
    _ = strings.map { retString = retString.replacingOccurrences(of: $0, with: "", options: .literal, range: nil) }
    return retString
}

[사용방법]

var retString = "abcdefghijklmn"

let ret = retString.removeAll(strings: ["cde", "klm"])

print("\(ret)")

abfghijn

 

2020/05/15 - [iOS/Swift] - String substring

2020/05/15 - [iOS/Swift] - Framework 경로

2020/05/15 - [iOS/Objective-C] - Frameworks 경로

2020/05/15 - [iOS/Objective-C] - iOS디바이스 설정창 이동

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/15 - [iOS/Objective-C] - Xcode 한글 깨짐 복구

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - WKWebView 스크린샷

2020/05/12 - [iOS/Swift] - json 포멧 체크

2020/05/12 - [iOS/Swift] - Access Control (접근 제한자)

2020/05/12 - [iOS/Swift] - WKWebview에서 tel, email, mailto, sms, facetime 처리

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

NSLog 출력 크기 제한 풀기  (0) 2020.05.18
탈옥후 안정화  (0) 2020.05.18
String substring  (0) 2020.05.15
Framework 경로  (0) 2020.05.15
Frameworks 경로  (0) 2020.05.15
블로그 이미지

SKY STORY

,