티스토리 뷰

2022.11.03 - [iOS개발/Swift 기본] - Swift 알림창(UIAlertController) 띄우기

 

Swift 알림창(UIAlertController) 띄우기

안녕하세요. 이번엔 간단한 기본 기능이지만 많이 쓰이는 알림창을 알아볼까합니다. 사실 방법 자체는 어려운게 아닌데 자주 까먹게 되더라고요. 일단 알림창이 뭔지 모르시는 분들을 위하여

world-of-larooly.tistory.com

이번 글은 해당 글의 다음 버전이라 생각하시면 될 것 같아요.

 

만약 창에 자신이 원하는 폰트를 적용하고 싶으신 분들을 위해 

코드를 만들어 놓았는데 저도 쓸겸 겸사겸사 올립니다. 

(참고로 버튼영역은 폰트 안바뀝니다!)

실제로 하시면 이렇게 됩니다.

 

*폰트의 경우에는 본인이 원하시는 폰트로 바꾸어 사용해주세요!*

func showCustomAlert(view:UIViewController,title : String ,text : String) {
    let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
    let titleAttributes = [NSAttributedString.Key.font: UIFont(name: "GangwonEduSaeeum-OTFMedium", size: 32)!, NSAttributedString.Key.foregroundColor: UIColor.blue]
    let titleString = NSAttributedString(string: title, attributes: titleAttributes)
    let messageAttributes = [NSAttributedString.Key.font: UIFont(name: "GangwonEduSaeeum-OTFMedium", size: 24)!, NSAttributedString.Key.foregroundColor: UIColor.black]
    let messageString = NSAttributedString(string: text, attributes: messageAttributes)
    alert.setValue(titleString, forKey: "attributedTitle")
    alert.setValue(messageString, forKey: "attributedMessage")
    let cancelAction = UIAlertAction(title: "확인", style: .cancel, handler: nil)
    cancelAction.setValue(UIColor.red, forKey: "titleTextColor")

    alert.addAction(cancelAction)

    view.present(alert, animated: true, completion: nil)
}

사용법은 아래와 같습니다.

showCustomAlert(view: self, title: "제목", text: "내용입니다.")

* 글씨 적용시 주의사항 

만약 본인이 설정하신 폰트가 잘 안나오시면 이름을 한번 확인해주세요.

일반적으로 아래처럼 쓰실텐데

UIFont(name: "GangwonEduSaeeum-OTFMedium", size: 32)

이때 이름을 무얼쓸지 잘 모르시는 분들은 스토리보드로 가셔서 적혀있는 이름을 한번 확인해주세요.

파일 이름X, 여기 나온 이름이 진짜입니다.

저거 파일이름이랑 약간 다르게 생긴 경우가 있어서 한번 확인하시는 걸 추천드립니다. 

 

그럼 오늘도 파이팅입니다.

댓글