第一张图片显示,每当我点击的CollectionView细胞,它会显示所选择的小区的ID在视图控制器的标题视图: 现在我的问题是,每当我整理收集视图的标题,然后点击单个细胞的ID已经一去不复返了:UICollectionViewCell失去上刷新迅速值3
我不知道现在该做什么,因为我无法找到有关此相关的帖子。这里是我的代码:
import UIKit
private let reuseIdentifier = "Cell"
class MovieCollectionViewController: UICollectionViewController {
private let leftAndRightPadding: CGFloat = 24.0
private let numberItemsPerRow: CGFloat = 2.0
private let heightAdustment: CGFloat = 90.0
var movies: [MOVIE]?
var filteredMovies: [MOVIE]?
var searchControllerMovie: UISearchController!
func filterContentForSearchTextMovie(searchText: String) {
filteredMovies = movies?.filter{
movie in
return (movie.movTitle?.lowercased().contains(searchText.lowercased()))!
}
collectionView?.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.searchControllerMovie = UISearchController(searchResultsController: nil)
self.searchControllerMovie.searchResultsUpdater = self
self.searchControllerMovie.searchBar.text = ""
self.searchControllerMovie.hidesNavigationBarDuringPresentation = false
self.searchControllerMovie.dimsBackgroundDuringPresentation = true
self.searchControllerMovie.obscuresBackgroundDuringPresentation = false
searchControllerMovie.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchControllerMovie.searchBar
//SPACING BETWEEN COLLECTION VIEW CELLS
let width = (collectionView!.frame.width - leftAndRightPadding)/numberItemsPerRow
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: width + heightAdustment)
//LOADER
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
fetchMovie()
// Do any additional setup after loading the view.
setupNavBarButtons()
}
func setupNavBarButtons() {
let sortAsc = UIBarButtonItem(image: UIImage(named: "arrow_up")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(sortMovieByAsc))
let sortDesc = UIBarButtonItem(image: UIImage(named: "arrow_down")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(sortMovieByDesc))
navigationItem.rightBarButtonItems = [sortDesc, sortAsc]
}
func sortMovieByAsc() {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
let queryItems = [NSURLQueryItem(name: "sortQuery", value: "Title Ascending")]
let urlComps = NSURLComponents(string: "http://192.168.81.118:8080/mobileweb/Android/getSortMovie")!
urlComps.queryItems = queryItems as [URLQueryItem]?
let URL = urlComps.url!
URLSession.shared.dataTask(with: URL, completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error!)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
self.movies = [MOVIE]()
for dictionary in json as! [[String: AnyObject]] {
let movie = MOVIE()
movie.movTitle = dictionary["TITLE"] as? String
movie.movImage = dictionary["PHOTO_DIR"] as? String
self.movies?.append(movie)
}
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
self.collectionView?.reloadData()
}
} catch let jsonError {
print(jsonError)
}
}).resume()
}
func sortMovieByDesc() {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
let queryItems = [NSURLQueryItem(name: "sortQuery", value: "Title Descending")]
let urlComps = NSURLComponents(string: "http://192.168.81.118:8080/mobileweb/Android/getSortMovie")!
urlComps.queryItems = queryItems as [URLQueryItem]?
let URL = urlComps.url!
URLSession.shared.dataTask(with: URL, completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error!)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
self.movies = [MOVIE]()
for dictionary in json as! [[String: AnyObject]] {
let movie = MOVIE()
movie.movTitle = dictionary["TITLE"] as? String
movie.movImage = dictionary["PHOTO_DIR"] as? String
self.movies?.append(movie)
}
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
self.collectionView?.reloadData()
}
self.collectionView?.reloadData()
} catch let jsonError {
print(jsonError)
}
}).resume()
}
func fetchMovie() {
let url = URL(string: "http://192.168.81.118:8080/mobileweb/Android/getMovie")
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error!)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
self.movies = [MOVIE]()
for dictionary in json as! [[String: AnyObject]] {
let movie = MOVIE()
movie.movTitle = dictionary["TITLE"] as? String
movie.movImage = dictionary["PHOTO_DIR"] as? String
movie.movID = dictionary["ID"] as? String
self.movies?.append(movie)
}
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
self.collectionView?.reloadData()
}
} catch let jsonError {
print(jsonError)
}
}).resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchControllerMovie.isActive && searchControllerMovie.searchBar.text != "" {
return (filteredMovies?.count)!
}
// #warning Incomplete implementation, return the number of items
return movies?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellIdentifier = "MovieCollectionViewCell"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? MovieCollectionViewCell
if searchControllerMovie.isActive && searchControllerMovie.searchBar.text != "" {
cell?.movie = filteredMovies?[indexPath.row]
} else {
// Configure the cell
cell?.movie = movies?[indexPath.row]
}
return cell!
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Row:\(indexPath.row)")
// let cell = collectionView.cellForItem(at: indexPath);
// self.performSegue(withIdentifier: "showDetail", sender: cell)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell) {
let movieDetail: MOVIE
if searchControllerMovie.isActive && searchControllerMovie.searchBar.text != "" {
movieDetail = (filteredMovies?[indexPath.item])!
}
else {
movieDetail = (movies?[indexPath.row])!
}
let controller = segue.destination as! MovieDetailsViewController
controller.movieDetail = movieDetail
}
}
}
extension MovieCollectionViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchTextMovie(searchText: searchController.searchBar.text!)
}
}
1 。https://i.stack.imgur.com/EJ2Se.png 2.https: //i.stack.imgur.com/FRIsV.png –
和movieDetail始终是正确的MOVIE对象,当您在此处打印movieDetail时:controller.movieDetail = movieDetail。 ? – Retterdesdialogs
我没有得到你的观点先生@rett –