-
iOS) Label에 입력되는 텍스트 중에 특정 단어의 크기나 색 바꾸기[펌]Programing Language/iOS(Swift) 2020. 4. 1. 17:16728x90반응형This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
========================================================================================================== If you already know the longest word you have to get the range of that word in the string. I prefer the NSString method rangeOfString: for this. You then create a NSMutableAttributedString from the string, with your default attributes. Finally you apply highlighting attributes to the range you figured out earlier. ========================================================================================================== let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar" let longestWord = "VeryLongWord" let longestWordRange = (longString as NSString).rangeOfString(longestWord) let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)]) attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange) label.attributedText = attributedString ========================================================================================================== Update for Swift 5.0 ========================================================================================================== let longestWordRange = (longString as NSString).range(of: longestWord) let attributedString = NSMutableAttributedString(string: longString, attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor : UIColor.white]) attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor : UIColor.red], range: longestWordRange) https://stackoverflow.com/a/29165718
ios swift: Is it possible to change the font style of a certain word in a string?
I am extracting from a DB contents as strings. With a method I extract the longest word out of this string. Now I would like to print out the entire string to a text label but would like to highl...
stackoverflow.com
728x90반응형'Programing Language > iOS(Swift)' 카테고리의 다른 글
iOS) 서버와 통신할때 get으로 보내는 단어 가 한글일때 인코딩 하는 방법 (0) 2020.04.10 iOS) HEX 코드를 UIColor 변수에 담기 (0) 2020.04.09 iOS) alert(알림) 만들기 (0) 2020.03.26 iOS ) 패스워드 관련 정규 표현식 [swift] (0) 2020.03.26 iOS) UITextField에 비밀번호 타입으로 값 입력하기 (0) 2020.03.26