I'm assuming you've initialized snackbar
inside a class func
or something like that. From this place self
represents your class DetailsInfoViewController
while you need the object of this class. If you initialize this object before snackbar
, you could write like this:
let controller: DetailsInfoViewController = ...
let snackbar = TTGSnackbar(message: "Attendance Update !", duration: .long, actionText: "SEND") { [weak controller] (snackbar) in
controller?.uncheck()
print("snack bar Action")
}
If it doesn't help you, please post the function code where you're creating snackbar
.
UPD:
With minimal changes of your code the following solution should work:
class DetailsInfoViewController: UIViewController {
var snackbarCount = 0
lazy var snackbar = TTGSnackbar(message: "Attendance Update !", duration: .long, actionText: "SEND") { (snackbar) in
self.uncheck()
print("snack bar Action")
}
func uncheck() {
print("snackbar uncheck function")
snackbarCount -= 1
checkSnackBar()
}
func checkSnackBar() {}
}
You found really tricky situation when your class requires self
inside closure as it initializes but this snackbar
variable initializes before we have ready-to-use self
variable. It means we need to initialize snackbar
after self
using lazy var
.
But I strongly suggests you to not write code as you wrote it. The TTHSnackbar author's example is designed to be placed in a function when this snackbar really need to be shown. For example:
class DetailsInfoViewController: UIViewController {
@IBAction func showSnackbarButtonTapped(_ sender: UIButton) {
let snackbar = TTGSnackbar(message: "TTGSnackBar !", duration: .middle, actionText: "Action!") { (snackbar) in
self.uncheck()
print("snack bar Action")
}
snackbar.show()
}
}
When it shows on the view it will be retained by this view.
UPD #2:
To show only one Snackbar at a time you could write like this:
class DetailsInfoViewController: UIViewController {
private weak var currentSnackbar: TTGSnackbar?
@IBAction func showSnackbarButtonTapped(_ sender: UIButton) {
if let snackbar = currentSnackbar {
snackbar.dismiss()
currentSnackbar = nil
}
let snackbar = TTGSnackbar(message: "TTGSnackBar !", duration: .middle, actionText: "Action!") { (snackbar) in
self.uncheck()
print("snack bar Action")
}
currentSnackbar = snackbar
snackbar.show()
}
}