SwiftでUIAlertControllerやUIAlertActionを実装するとコード量が多く見辛いというデメリットが有る。
そんな悩みを解決してくれるのが「Alertift」というライブラリ。
基本情報
Alertiftの基本情報。
CocoaPodsまたはCarthageで導入可能。
実装コード
実際に実装すると以下のようになる。
Alertift.alert(title: "タイトル", message: "メッセージ")
.action(.default("OK")) { [unowned self] in
print("OK")
}
.action(.destructive("削除")) { [unowned self] in
print("delete")
}
.action(.cancel("キャンセル"))
.show(on: self)
最後の.show(on: self)
がないと表示されないので注意が必要。
UIAlertController.Style.actionSheet
を実装したい場合は以下の通り。
Alertift.actionSheet(title: "タイトル", message: "メッセージ")
.action(.default("OK")) { [unowned self] in
print("OK")
}
.action(.destructive("削除")) { [unowned self] in
print("delete")
}
.action(.cancel("キャンセル"))
.show(on: self)
UITextFieldを組み込みたい時は以下の通り。
Alertift.alert(title: "タイトル", message: "メッセージ")
.textField { textField in
textField.placeholder = ""
}
.handleTextFieldTextDidChange { textField, index in
print(textField.text ?? "")
}
.action(.cancel("キャンセル"))
.show(on: self)
参考文献
Swiftのお役立ち情報