[iOS] Toast 메시지 구현하기

Hoojeong Kim·2022년 6월 22일
3
post-thumbnail

안드로이드에서 사용하는 Toast 메시지를 iOS에서도 쓰고 싶어졌다.
iOS에서는 관련 라이브러리로 지원하지 않고 직접 만들어야 한다.
toast 메시지 자체를 권장하지 않는듯


하지만 세상에는 멋진 개발자들이 많고,, 약간의 구글링과 깃허브를 살펴보면 라이브러리를 발견할 수 있다.

scalessec/Toast-Swift

코드 한 두줄이면 뚝딱!


이 라이브러리를 사용해도 되지만!
그냥 직접 만들어봤다. 히히

func showToast(_ message : String, withDuration: Double, delay: Double) {
	let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7)
    toastLabel.textColor = UIColor.white
    toastLabel.font = UIFont.systemFont(ofSize: 14.0)
    toastLabel.textAlignment = .center
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 16
    toastLabel.clipsToBounds  =  true
        
    self.view.addSubview(toastLabel)
        
    UIView.animate(withDuration: withDuration, delay: delay, options: .curveEaseOut, animations: {
		toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
	    toastLabel.removeFromSuperview()
    })
}

실행 결과

나는 버튼을 누르면 toast 메시지가 나오도록 했고, withDuration 값과 delay 값은 각각 2, 1.5로 설정했다.

안드로이드에서 보던 토스트 메시지 만들기 성공!

profile
나 애기 개발자 👶🏻

0개의 댓글