以前投稿した、「【Swift】iOSでToast風のメッセージ表示機能を実装する」で紹介した Toast 風のメッセージ表示機能について、文字数に合わせたサイズで表示を修正したので備忘録も兼ねてまとめ。
ただし、画面からはみ出るほどの文字数では動作確認していませんのでご注意ください!
「送信しました」などの短いメッセージを表示することを前提としています。
コードは下記のとおりです。
class Toast {
internal static func show(_ text: String, _ parent: UIView) {
let label = UILabel()
var bottomPadding = 15.0
if #available(iOS 13.0, *) {
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
if let window = windowScene?.windows.first {
if window.safeAreaInsets.bottom > 0 {
bottomPadding = window.safeAreaInsets.bottom
}
}
}
label.backgroundColor = UIColor.black.withAlphaComponent(0.6)
label.textColor = UIColor.white
label.textAlignment = .center;
label.text = text
label.sizeToFit()
label.layer.cornerRadius = 10
label.clipsToBounds = true
let width = label.intrinsicContentSize.width + 25
let height = label.intrinsicContentSize.height + 15
label.frame = CGRect(x: parent.frame.size.width / 2 - (width / 2), y: parent.frame.size.height - height - bottomPadding, width: width, height: height)
parent.addSubview(label)
UIView.animate(withDuration: 1.0, delay: 3.0, options: .curveEaseOut, animations: {
label.alpha = 0.0
}, completion: { _ in
label.removeFromSuperview()
})
}
}
上記をプロジェクトに追加し、メッセージを表示したいタイミングで下記を実行してください。
Toast.show("Toast メッセージの内容", self.view)
問題がなければ、Toast っぽい見た目でメッセージが表示されるはずです。
今回は長文には対応していませんが…時間に余裕ができたら、文字の折り返しにも対応したいと思います!
以上、Swift で Toast 風メッセージを表示する方法についてでした。
ご参考になれば幸いです。