카테고리 없음

swift 네비게이션 바 타이틀 색상 커트텀해보기

kingarthur 2024. 9. 3. 18:11

이유는 없다. 그냥 디테일?? 갸우 해보고 싶어서 했는데

잘 안되서 이리저리 도움을 받고 성공했다 ~~ 

 

다음에도 잘 이용해먹자 

 private func configureNavigationBar() {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.barTintColor = .darkGray // 네비게이션 바 배경색 설정
        }
    }
    // 네비게이션 바 커스텀 설정
    private func configureNavigationBarTitle() {
        // 전체 타이틀 텍스트
        let fullTitle = "300s Workout"
         
        // 특정 문자의 색상과 스타일을 지정
        let attributedString = NSMutableAttributedString(string: fullTitle)
        let rangeOfColorChange = (fullTitle as NSString).range(of: "s") // 색상을 바꾸고 싶은 부분
        
        // 색상 및 폰트 설정
        attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: rangeOfColorChange) // 특정 문자의 색상
        attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: rangeOfColorChange) // 특정 문자의 폰트
        // 전체 타이틀 색상 설정 (타이틀 전체가 아닌 부분 색상 설정)
          let defaultColor = UIColor.white
          let defaultFont = UIFont.systemFont(ofSize: 18, weight: .regular)
          
          attributedString.addAttribute(.foregroundColor, value: defaultColor, range: NSRange(location: 0, length: fullTitle.count))
          attributedString.addAttribute(.font, value: defaultFont, range: NSRange(location: 0, length: fullTitle.count))
          
          // 특정 문자의 색상과 폰트가 우선 적용되도록 설정
          attributedString.addAttributes([.foregroundColor: UIColor.red, .font: UIFont.boldSystemFont(ofSize: 18)], range: rangeOfColorChange)
        
        // 전체 타이틀 색상 설정 (타이틀 전체가 아닌 부분 색상 설정)
        let titleLabel = UILabel()
        titleLabel.attributedText = attributedString
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel // 커스텀 타이틀 설정
    }

 

이렇게 하면 내가 원하는 문구에 색상을 넣고 타이틀 색상도 지정가능하다구 ~ 

앞으로도 자주보자구