이 글을 쓰게 된 이유는 다음과 같습니다.
맥덕 앱을 개발하는 중,
기존의 iOS에서 제공하는 기본적인 UIAlertController의 일부만 커스텀하면 되는 상황이였는데
자료를 찾다보니 정보가 분산되어 있었습니다.
또한 저처럼 텍스트의 font, size, color와background color를 바꾸는 코드가 없었습니다.
(+ 일부 텍스트의 color만 변경)
그래서 코드 및 모든 참고자료를공유합니다.
UIAlertController 커스텀을 찾으시던 분들에게 도움이 되었으면 좋겠습니다.
아래 이미지는 UIAlertController를 커스텀한 모습입니다.
아래는 전체 코드입니다.
제가 찾아봤을 때 Title과 Message(아래 코드엔 없음)가 아닌,
Action(버튼)의 text는 color만 변경이 가능하고
font나 size는 변경이 불가했습니다.
(만약 아시는 분이 있으시다면 댓글로 알려주시면 감사하겠습니다.)
let text: String = "먹어봤던 맥주 리뷰 1개만 남기면 모든 리뷰를 보실 수 있어요!"
let attributeString = NSMutableAttributedString(string: text) // 텍스트 일부분 색상, 폰트 변경 - https://icksw.tistory.com/152
let font = UIFont(name: "NotoSansKR-Medium", size: 16)
attributeString.addAttribute(.font, value: font!, range: (text as NSString).range(of: "\(text)")) // 폰트 적용.
attributeString.addAttribute(.foregroundColor, value: UIColor.mainYellow, range: (text as NSString).range(of: "먹어봤던 맥주 리뷰 1개")) // '먹어봤던 맥주 리뷰 1개' 부분 색상 옐로우 변경.
attributeString.addAttribute(.foregroundColor, value: UIColor.mainWhite, range: (text as NSString).range(of: "만 남기면 모든 리뷰를 보실 수 있어요!")) // 나머지 부분 색상 화이트 변경.
let alertController = UIAlertController(title: text, message: "", preferredStyle: UIAlertController.Style.alert)
alertController.setValue(attributeString, forKey: "attributedTitle") // 폰트 및 색상 적용.
let reviewWrite = UIAlertAction(title: "리뷰쓰기", style: .cancel, handler: {
action in
print("리뷰쓰기 버튼 클릭함.")
})
let cancle = UIAlertAction(title: "나중에하기", style: .default, handler: nil)
reviewWrite.setValue(UIColor.mainYellow, forKey: "titleTextColor") // 색상 적용.
cancle.setValue(UIColor.mainWhite, forKey: "titleTextColor") // 색상 적용.
alertController.addAction(reviewWrite)
alertController.addAction(cancle)
// 배경색 변경
alertController.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .subBlack3
present(alertController, animated: true, completion: nil)
.setValue의 forKey의 모든 종류는 다음과 같습니다.
["_title", "_titleTextAlignment", "_enabled", "_checked", "_isPreferred", "_imageTintColor", "_titleTextColor", "_style", "_handler", "_simpleHandler", "_image", "_shouldDismissHandler", "__descriptiveText", "_contentViewController", "_keyCommandInput", "_keyCommandModifierFlags", "__representer", "__interfaceActionRepresentation", "__alertController"]
참고 자료
UIAlertController 배경색 변경
https://stackoverflow.com/questions/40835803/swift-uialertcontroller-background-color
UIAlertController Title & Message 폰트, 색상, 사이즈 변경
https://stackoverflow.com/questions/44195691/how-to-set-the-custom-font-for-uialertaciton-in-swift
https://www.hackingwithswift.com/forums/swift/how-change-font-size-at-uialertaction/3277
https://stackoverflow.com/questions/42793471/uialertaction-with-different-color-button-text
.setValue의 forKey 종류
https://stackoverflow.com/questions/30056236/uialertaction-list-of-values
최근댓글