Я создал измененный пейджинговый UIScrollView. Я реализовал лениво загруженные страницы, однако я хотел бы удалить контент, который больше не отображается на экране, чтобы сохранить память. В настоящее время я удаляю только подпредставления из UIScrollView, но не содержимое.
Ниже приведен код, который у меня есть до сих пор, как выполнить динамическое удаление контента.
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
// MARK: - Properties
var scrollView: UIScrollView!
let numPages = 6
var pages = [UIView?]()
var imageViews:[UIImageView] = [UIImageView](){
didSet{
print("imageViews.count: \(imageViews.count)")
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
_ = setupInitialPages
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: view.bounds)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.isPagingEnabled = true
view.addSubview(self.scrollView)
scrollView.backgroundColor = UIColor.blue
scrollView.delegate = self
scrollView.indicatorStyle = .white
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
pages = [UIView?](repeating: nil, count: numPages)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Initial Setup
lazy var setupInitialPages: Void = {
adjustScrollView()
loadPage(0)
loadPage(1)
}()
// MARK: - Utilities
fileprivate func removeAnyImages() {
for page in pages where page != nil {
page?.removeFromSuperview()
}
}
fileprivate func adjustScrollView() {
scrollView.contentSize =
CGSize(width: scrollView.frame.width * CGFloat(numPages),
height: scrollView.frame.height - topLayoutGuide.length)
}
func getImage(page:Int)->UIImage{
let resourceName = String(page + 1)
return #imageLiteral(resourceName: resourceName)
}
fileprivate func loadPage(_ page: Int) {
guard page < numPages && page != -1 else { return }
if pages[page] == nil {
let newImageView = getRecycledImageView()
newImageView.image = getImage(page: page)
newImageView.contentMode = .scaleAspectFit
newImageView.backgroundColor = UIColor.yellow
var frame = scrollView.frame
frame.origin.x = frame.width * CGFloat(page)
frame.origin.y = -self.topLayoutGuide.length
frame.size.height += self.topLayoutGuide.length
let canvasView = UIView(frame: frame)
scrollView.addSubview(canvasView)
newImageView.translatesAutoresizingMaskIntoConstraints = false
canvasView.addSubview(newImageView)
NSLayoutConstraint.activate([
(newImageView.leadingAnchor.constraint(equalTo: canvasView.leadingAnchor)),
(newImageView.trailingAnchor.constraint(equalTo: canvasView.trailingAnchor)),
(newImageView.topAnchor.constraint(equalTo: canvasView.topAnchor)),
(newImageView.bottomAnchor.constraint(equalTo: canvasView.bottomAnchor))
])
pages[page] = canvasView
// }
}
}
func getRecycledImageView()->UIImageView{
let unusedImageViews = imageViews.filter { (imageView) -> Bool in
return imageView.isDescendant(of: scrollView) == false
}
if let unusedImageView = unusedImageViews.first{
print("reusing imageView")
return unusedImageView
}else{
let imageView = UIImageView()
imageViews.append(imageView)
return imageView
}
}
fileprivate func loadCurrentPages(page: Int) {
guard (page > 0 && page + 1 < numPages) || transitioning else { return }
// Remove all of the images and start over.
removeAnyImages()
pages = [UIView?](repeating: nil, count: numPages)
loadPage(Int(page) - 1)
loadPage(Int(page))
loadPage(Int(page) + 1)
}
fileprivate func gotoPage(page: Int, animated: Bool) {
loadCurrentPages(page: page)
var bounds = scrollView.bounds
bounds.origin.x = bounds.width * CGFloat(page)
bounds.origin.y = 0
scrollView.scrollRectToVisible(bounds, animated: animated)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
let page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1
loadCurrentPages(page: Int(page))
}
}