Swift

Swift_ Toast 만들기

JunsC 2024. 8. 2. 12:09
728x90

AOS 에서는 토스트 메시지 만들기 정말정말 쉽다

그냥 
Toast. 하면 자동완성으로 만들어지기 때문이다

 

하지만 Swift 는 지원해주는 부분들이 의외로 적다고 느껴진다

그래서 토스트 메시지를 커스텀하여 만들어야 하는데 

내가 사용한 코드를 적어놓으려 한다

 

class ToastManager {
    static let shared = ToastManager()
    
    private init() {}
    
    func showToast(on viewController: UIViewController, message: String, withDuration duration: Double = 2.0, delay: Double = 0.5) {
        let toastLabel = UILabel()
        
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        toastLabel.textColor = UIColor.white
        toastLabel.font = UIFont.systemFont(ofSize: 25.0, weight: .bold) //
        toastLabel.textAlignment = .center
        toastLabel.text = message
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10
        toastLabel.clipsToBounds = true
        toastLabel.numberOfLines = 0
        toastLabel.translatesAutoresizingMaskIntoConstraints = false
        
        let maxWidth = UIScreen.main.bounds.width - 40
        let maxSize = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)
        let expectedSize = toastLabel.sizeThatFits(maxSize)
        
        toastLabel.frame.size = CGSize(width: expectedSize.width + 20, height: expectedSize.height + 20)
        
        if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
            window.addSubview(toastLabel)
            
            NSLayoutConstraint.activate([
                toastLabel.centerXAnchor.constraint(equalTo: window.centerXAnchor),
                toastLabel.bottomAnchor.constraint(equalTo: window.safeAreaLayoutGuide.bottomAnchor, constant: -50),
                toastLabel.widthAnchor.constraint(equalToConstant: toastLabel.frame.width),
                toastLabel.heightAnchor.constraint(equalToConstant: toastLabel.frame.height)
            ])
            
            UIView.animate(withDuration: duration, delay: delay, options: .curveEaseOut, animations: {
                toastLabel.alpha = 0.0
            }, completion: { isCompleted in
                toastLabel.removeFromSuperview()
            })
        }
    }
}

 

짜란 

 

구글링의 힘이다 

그리고 ChatGpt 의 힘이다...

원래 아니여도 구현은 가능하지만 시간이 좀 걸릴 뿐...

728x90
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."