cozzin
코찐 기술 블로그
cozzin
전체 방문자
오늘
어제
  • 분류 전체보기
    • Kotlin
    • 백엔드
    • iOS
      • Swift
      • SwiftUI
      • Combine
      • Architecture
    • 개발환경
    • 세미나
    • 생각정리
    • 스터디
    • CS
      • Refactoring
      • OS

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • LinkedIn
  • 강의

공지사항

인기 글

태그

  • darkmode
  • Warning
  • Combine
  • ios
  • 리팩토링
  • Ribs
  • WWDC
  • multicast
  • 테스트
  • XCode
  • slide-over
  • WWDC21
  • CS
  • 컴퓨터공학
  • 운영체제
  • 디자인패턴
  • os
  • Swift
  • SwiftUI
  • 워닝제거

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
cozzin

코찐 기술 블로그

[iOS] UITextField placeholder color 변경하기
iOS

[iOS] UITextField placeholder color 변경하기

2021. 1. 20. 16:22
반응형

안녕하세요 코찐입니다.

UITextField를 쓸 때 플레이스 홀더 텍스트의 색상을 변경할 일이 있습니다.

textField.placeholderColor 로 지정가능하면 좋을텐데 그런 변수는 없습니다...

그래서 매번 검색해서 찾게되는데요.

다음에 또 찾을 수 있도록 기록차 남겨둡니다.

 

해결책

https://stackoverflow.com/questions/1340224/iphone-uitextfield-change-placeholder-text-color

 

iPhone UITextField - Change placeholder text color

I'd like to change the color of the placeholder text I set in my UITextField controls, to make it black. I'd prefer to do this without using normal text as the placeholder and having to override a...

stackoverflow.com

textField.attributedPlaceholder = NSAttributedString(string: "플레이스홀더", attributes: [.foregroundColor: UIColor.systemGray])

이런식으로 AtrributedString을 만들어서 넣어주면 됩니다. 

 

조금 더 편하게

저는 AtrributedString 사용하는게 번거롭다고 생각되어서 Extension을 만들어보겠습니다.

public extension UITextField {
    
    func setPlaceholderColor(_ placeholderColor: UIColor) {
        attributedPlaceholder = NSAttributedString(
            string: placeholder ?? "",
            attributes: [
                .foregroundColor: placeholderColor,
                .font: font
            ].compactMapValues { $0 }
        )
    }
    
}

 

그러면 사용하는 쪽에서는 다음과 같이 쓸 수 있습니다.

textField.placeholder = "플레이스홀더"
textField.setPlaceholderColor(.systemGray)

 

String을 넣고 Color를 지정하는 순서를 지켜야한다는 점이 단점이긴 합니다.

그래도 좀 더 간편하게 사용할 수 있다고 생각해서 공유합니다 :)

반응형
저작자표시

'iOS' 카테고리의 다른 글

워닝 제거하기: Implicit import of bridging header '{YourApp}-Bridging-Header.h' via module '{YourApp}' is deprecated and will be removed in a later version of Swift  (0) 2021.01.29
[iOS] grouped style tableView에서 위아래 여백 제거하기  (0) 2021.01.28
[iOS] 이슈 해결: CloudKit integration does not support unique constraints  (0) 2021.01.23
[iOS] overrideUserInterfaceStyle 부분 적용하기  (0) 2021.01.20
Xcode 파일별 빌드 속도 측정  (0) 2021.01.04
    'iOS' 카테고리의 다른 글
    • [iOS] grouped style tableView에서 위아래 여백 제거하기
    • [iOS] 이슈 해결: CloudKit integration does not support unique constraints
    • [iOS] overrideUserInterfaceStyle 부분 적용하기
    • Xcode 파일별 빌드 속도 측정
    cozzin
    cozzin
    Software Engineer

    티스토리툴바