Swift/학습

[Swift] UIAlertController 안에 CustomView 를 넣어보자!

언클린 2022. 1. 13. 21:41
728x90

이번 글에서는 표준 UIAlertController 안에 커스텀 뷰를 넣어보는 작업을 진행해 보겠습니다.

네... 별로 사용할 경우는 없을 것 같습니다.

무리해서 띄우는 것보다 이쁘게 커스텀을 만드는 것이 좋다고 생각합니다.

저 같은 경우는 이전 회사에서 요구해서 살짝 한 번 다뤄봤었는데 오랜만에 기억이 나서

공유드리겠습니다 (0_0)


1. Alert 만들어 보기

간단한 Alert 을 만들어 보겠습니다. 

        let alert = UIAlertController(title: "Test", message: "Message", preferredStyle: .alert)

        let action = UIAlertAction(title: "Confirm", style: .default)
        alert.addAction(action)
        
        self.present(alert, animated: true)

 

2. UIAlertController 확장

커스텀 뷰를 넣는 로직을 Extension 을 사용하여 구현하였습니다.

우선 저 같은 경우는 2가지 조건을 주었습니다.

  1. 기존에 입력한 title 과 message 는 초기화
  2. 커스텀 뷰는 비율로 표시 (Alert 의 너비는 한계가 존재해서...)
extension UIAlertController {
    ///
    /// 커스텀 다이어로그를 설정
    ///
    public func customViewAlert(_ view: UIView) {
        self.title = nil
        self.message = nil
        
        let input = view
        self.view.addSubview(input)
        
        let topMargin: CGFloat = 20.0
        let leftMargin: CGFloat = 16.0
        let btnHeight: CGFloat = 44.0
        let alertWidth = self.view.frame.size.width - (2 * leftMargin)
        
        let viewWidth = (alertWidth / input.frame.width) * input.frame.width
        let viewHeight = (alertWidth / input.frame.width) * input.frame.height
        
        input.frame = CGRect(x: leftMargin, y: topMargin, width: viewWidth, height: viewHeight)
        
        let indicatorConstraint = NSLayoutConstraint(item: self.view as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: viewHeight + btnHeight + topMargin + leftMargin)
        indicatorConstraint.identifier = "indicatorConstraint"
        self.view.addConstraint(indicatorConstraint)
    }
}

 

3. 적용

마무리로 적용을 해보겠습니다.

let alert = UIAlertController(title: "Test", message: "Message", preferredStyle: .alert)
DispatchQueue.main.async {
    let customView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
    customView.backgroundColor = .blue
    alert.customViewAlert(customView)
}

let action = UIAlertAction(title: "Confirm", style: .default)
alert.addAction(action)

self.present(alert, animated: true)

 

마무리

이렇게 해서 간단하게 Alert 에 커스텀 뷰를 넣어보았습니다. (^^)

도움이 되었으면 좋겠습니다.

감사합니다!


환경 

Xcode 13.2.1

Swift 5

 

 

 

 

728x90