Как сделать так чтобы при перелистывании на последней странице появилась кнопка и по клику на нее приложение закрывалось?
Данные:
- Есть простенькое приложение презентации мобильного приложения.
Сделано на
UIPageView. - Есть приветственный экран "Welcome" (показывается после того как пользователь свайпнул последний скрин презентации или нажал кнопку "Закрыть презентацию" на последнем скрине презентации)
- Есть контроллер
UIPageViewчерез который определяются в коде (в storyboard только один контроллер который отвечает за отображение этих скринов при перелистывании презентации) следующие скрины.
Также в приложении стоит параметр специального ключа который запоминает что юзер вошел уже с этим приложением и при следующем входе презентация показываться не будет, вместо нее только скрин "Welcome".(Для того чтобы зайти заново в презентацию приложения, необходимо удалить аппку из телефона/симулятора и заново перезапустить по кнопке "Run" в Xcode)
Задача:
- На последнем скрине при перелистывании должна появится кнопка "Закрыть презентацию"(при клике на нее презентация слайдов закрывается и появляется экран "Welcome"). Cейчас там кнопка не показывается и при перелистывании после последнего слайда сразу свайпом идет скрин "Welcome".
Ссылка на само приложение тут - Github ветка приложения
Прикрепляю на всякий случай код для быстрого ознакомления:
ViewController.swift
import UIKit
class ViewController: UIViewController {
//this method allows to call the method startPresentation
override func viewDidAppear(_ animated: Bool) {
/*
the viewDidAppear method is triggered immediately after the application is loaded, after the View is displayed on the screen
*/
super.viewDidAppear(animated)
startPresentation()
}
// method which runs PageViewController
func startPresentation(){
// extend realization for special key when presentation is closed
let userDefaults = UserDefaults.standard
let presentationWasViewed = userDefaults.bool(forKey: "presentationWasViewed")
if presentationWasViewed == false {
if let pageViewController = storyboard?.instantiateViewController(identifier: "PageViewController") as? PageViewController {
// if we could show ViewController, - we need show View Controller
present(pageViewController, animated: true, completion: nil)
//попытка вывести кнопку на последний скрин
//ContentViewController.closePresentationAction()
}
}
}
/*
func startPresentation(){
if let pageViewController = storyboard?.instantiateViewController(identifier: "PageViewController") as? PageViewController {
// if we could show ViewController, - we need show View Controller
present(pageViewController, animated: true, completion: nil)
}
}
*/
}
ContentViewController.swift
import UIKit
class ContentViewController: UIViewController {
@IBOutlet weak var presentTextLabel: UILabel!
@IBOutlet weak var emojiLabel: UILabel!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var closePresentationButton: UIButton!
//let tapPresentation = UIPageViewController()
var presentText = ""
var emoji = ""
var currentPage = 0 // number of the current page
var numberOfPages = 0 // total number of pages
var closePresButton: UIButton? // переменная для вывода кнопки на глобальный уровень
override func viewDidLoad() {
super.viewDidLoad()
//кнопка изначально скрыта (пока не дойдет до последнего скрина)
closePresentationButton.isHidden = true
presentTextLabel.text = presentText
emojiLabel.text = emoji
pageControl.numberOfPages = numberOfPages
pageControl.currentPage = currentPage
closePresentationButton = closePresButton
//еще раз попытка показать скрытую кнопку именно на последнем скрине
//closePresentationButton.isHidden = false
}
//тут кнопка которая должна появится при просмотре последнего скрина
@IBAction func closePresentationAction(_ sender: UIButton) {
let closePresentation = PageViewController()
closePresentation.closePresentationButtonFunc()
}
}
PageViewContrller.swift
import UIKit
class PageViewController: UIPageViewController {
let presentScreenContent = [
"Первая страница презентации, - рассказывает о сути приложения",
"Вторая страница презентации, - рассказывает о какой-то фишке приложения",
"Третья страница презентации, - показывает еще что-то очен интересное в виде картинки и анимации",
"Последяя страница презентации, - какое-то приятное пожелание пользователю", ""
]
let emojiArray = [
"?","??","?","?", ""
]
override func viewDidLoad() {
super.viewDidLoad()
// we need to assign the class as a delegate of the protocol datasource
dataSource = self
//declare method ContentViewController
if let contentViewController = showViewControllerAtIndex(0){
//method which create array of the View Controllers
setViewControllers([contentViewController], direction: .forward, animated: true, completion: nil)
}
closePresentationButtonFunc()
}
//method which allows for us to create ViewController
func showViewControllerAtIndex(_ index: Int) -> ContentViewController? {
guard index >= 0 else { return nil }
guard index < presentScreenContent.count else { return nil }
guard let contentViewController = storyboard?.instantiateViewController(identifier: "ContentViewController")
as? ContentViewController else { return nil }
contentViewController.presentText = presentScreenContent[index]
contentViewController.emoji = emojiArray[index]
contentViewController.currentPage = index
contentViewController.numberOfPages = presentScreenContent.count
//contentViewController.buttonForClose = closePresentationButtonFunc
// пока оно выводит просто свайпом закрытие презентации
if contentViewController.currentPage == presentScreenContent.count-1{
closePresentationButtonFunc()
}
return contentViewController
}
//функция которая работает с параметрами закрытия презентации
func closePresentationButtonFunc(){
//-------------
//сreating a key that allows you to save the state of the presentation before it closes
let userDefaults = UserDefaults.standard
userDefaults.set(true, forKey: "presentationWasViewed")
//method which close controller
dismiss(animated: true, completion: nil)
//------------
}
}
extension PageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
// get number of current page
var pageNumber = (viewController as! ContentViewController).currentPage
pageNumber -= 1
return showViewControllerAtIndex(pageNumber)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
// get number of current page
var pageNumber = (viewController as! ContentViewController).currentPage
pageNumber += 1
return showViewControllerAtIndex(pageNumber)
}
}
Ответы (1 шт):
Я посмотрел проект и внес ряд правок (см комментарии). По поводу видимости кнопки - я добавил переменную presentationButtonIsHidden, которая присваивается при инициализации очередного контроллера, это происходит раньше, чем отрабатывает viewDidLoad, поэтому затем эту переменную можно использовать как closePresentationButton.isHidden = presentationButtonIsHidden
class ContentViewController: UIViewController {
@IBOutlet weak var presentTextLabel: UILabel!
@IBOutlet weak var emojiLabel: UILabel!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var closePresentationButton: UIButton!
var presentText = ""
var emoji = ""
var currentPage = 0 // number of the current page
var numberOfPages = 0 // total number of pages
var presentationButtonIsHidden = true // -- 1 добавлена переменная
override func viewDidLoad() {
super.viewDidLoad()
//кнопка изначально скрыта (пока не дойдет до последнего скрина)
closePresentationButton.isHidden = presentationButtonIsHidden // -- 2 присваиваем
presentTextLabel.text = presentText
emojiLabel.text = emoji
pageControl.numberOfPages = numberOfPages
pageControl.currentPage = currentPage
}
//тут кнопка которая должна появится при просмотре последнего скрина
@IBAction func closePresentationAction(_ sender: UIButton) {
// -- 3 закрываем презентацию
let userDefaults = UserDefaults.standard
userDefaults.set(true, forKey: "presentationWasViewed")
dismiss(animated: true, completion: nil)
}
}
class PageViewController: UIPageViewController {
// -- 1 убрана пустая страница
let presentScreenContent = [
"Первая страница презентации, - рассказывает о сути приложения",
"Вторая страница презентации, - рассказывает о какой-то фишке приложения",
"Третья страница презентации, - показывает еще что-то очен интересное в виде картинки и анимации",
"Последяя страница презентации, - какое-то приятное пожелание пользователю"
]
// -- 2 убрана пустая страница
let emojiArray = [
"?","??","?","?"
]
override func viewDidLoad() {
super.viewDidLoad()
// we need to assign the class as a delegate of the protocol datasource
dataSource = self
//declare method ContentViewController
if let contentViewController = showViewControllerAtIndex(0){
//method which create array of the View Controllers
setViewControllers([contentViewController], direction: .forward, animated: true, completion: nil)
}
}
//method which allows for us to create ViewController
func showViewControllerAtIndex(_ index: Int) -> ContentViewController? {
guard index >= 0 else { return nil }
guard index < presentScreenContent.count else { return nil }
guard let contentViewController = storyboard?.instantiateViewController(identifier: "ContentViewController")
as? ContentViewController else { return nil }
contentViewController.presentText = presentScreenContent[index]
contentViewController.emoji = emojiArray[index]
contentViewController.currentPage = index
contentViewController.numberOfPages = presentScreenContent.count
let isLastPage = (index == presentScreenContent.count - 1)
contentViewController.presentationButtonIsHidden = !isLastPage // -- 3 управляем видимостью кнопки
return contentViewController
}
}
