본문으로 바로가기

[iOS] Toast 메세지 구현

category ios 개발/iOS 2022. 10. 8. 15:49

1. label 패딩주기

토스트메세지가 label크기랑 딱 맞으면 안이쁘기때문에 패딩을 줌

class PaddingLabel: UILabel {
    private var padding = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
    
    override var intrinsicContentSize: CGSize {
        var contentSize = super.intrinsicContentSize
        contentSize.height += padding.top + padding.bottom
        contentSize.width += padding.left + padding.right
        
        return contentSize
    }
    
    convenience init(text: String) {
        self.init()
        self.numberOfLines = 0
        self.textAlignment = .center
        self.text = text
        let contentSize = intrinsicContentSize
        self.frame.size = contentSize
    }
}

2. 토스트 메세지

UIView를 extension 해서 만들음

/// message: message
/// bottomPosition: view의 bottom에서 얼마나 떨어질지
/// showDuration: 보여지고 사라지는 시간
/// duration: 보여지는 시간
/// autoHide: 자동으로 사라질지 여부 (해당값이 true일경우 duration은 무의미)
@discardableResult
func toast(
	message: String,
	bottomPosition: CGFloat,
	showDuration: TimeInterval,
    duration: TimeInterval = 0,
	autoHide: Bool = true
) -> UIView {
	let label = PaddingLabel(text: message)
    label.text = message
    let x = (frame.width / 2) - (label.frame.width / 2)
	label.frame.origin = CGPoint(x: x, y: frame.height - bottomPosition)
        
    label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
    label.textColor = .white
	label.layer.cornerRadius = label.frame.height / 2
	label.layer.masksToBounds = true
	showToast(view: label, showDuration: showDuration, duration: duration, autoHide: autoHide)
        
    return label
}
/// 토스트 보이기
    func showToast(view: UIView, showDuration: TimeInterval, duration: TimeInterval, autoHide: Bool) {
        addSubview(view)
        view.alpha = 0
        
        UIView.animate(withDuration: showDuration, delay: 0, options: [.curveEaseIn]) {
            view.alpha = 1
        } completion: { [weak self] isFinish in
            guard let self = self else { return }
            if autoHide && isFinish {
                self.hideToast(view: view, hideDuration: showDuration, duration: duration)
            }
        }
    }
/// 토스트 사라지기
    /// (해당 함수를 직접 호출할경우 duration만큼 delay후 사라짐)
    func hideToast(view: UIView, hideDuration: TimeInterval, duration: TimeInterval = 0) {
        UIView.animate(withDuration: hideDuration, delay: duration, options: [.curveEaseOut]) {
            view.alpha = 0
        } completion: { _ in
            view.removeFromSuperview()
        }
    }

3. 사용

 @IBAction func toast(_ sender: UIButton) {
        guard let text = tf.text,
              !text.isEmpty else {
            return
        }
        
        view.toast(message: text, bottomPosition: 300, showDuration: 0.5, duration: 2)
    }
    
    @IBAction func showToast(_ sender: UIButton) {
        guard let text = tf.text,
              !text.isEmpty else {
            return
        }
        
        toastView = view.toast(message: text, bottomPosition: 300, showDuration: 0.5, autoHide: false)
    }
    
    @IBAction func hideToast(_ sender: UIButton) {
        guard let toast = toastView else {
            return
        }
        
        view.hideToast(view: toast, hideDuration: 0.5)
        toastView = nil
    }

toast함수의 audoHide 가 true일경우 보여주고 사라지는것까지 자동

false일경우 보여주는건 자동이지만 사라지는건 hideToast함수를 직접 실행해줘야함

전체코드

https://github.com/jmindeveloper/Toast

 

GitHub - jmindeveloper/Toast: ios toastMessage

ios toastMessage. Contribute to jmindeveloper/Toast development by creating an account on GitHub.

github.com