[英]how to pass data from tableview to tableview like instagram? swift
If users search, the results come out on first table View(searchHome). 如果用户搜索,结果将显示在第一个表View(searchHome)上。
And If I select one cell, I can see detail info of this on to next tableView(bookDetail). 如果选择一个单元格,则可以在下一个tableView(bookDetail)上看到其详细信息。
So in bookDetail, so only one cell exists like instagram.(it's like instagram my page. In my page I can see many pictures, but I select one, I can only 1 picture with detail info). 因此,在bookDetail中,只有一个像instagram这样的单元格存在。(就像instagram我的页面。在我的页面中,我可以看到很多图片,但是我选择了一张,就只能显示1张带有详细信息的图片)。
but the data of searchHome is not passed to the detailBook. 但是searchHome的数据不会传递到detailBook。
there are 3 classes with this issue. 这个问题有3个班级。
One is class for passing data(BookAPIResult) 一种是用于传递数据的类(BookAPIResult)
Another is class of UITableViewController for search(SearchHome) 另一个是用于搜索的UITableViewController类(SearchHome)
The other is class of UITableViewController for detailIndo(bookDetail) 另一个是detailIndo(bookDetail)的UITableViewController的类
class BookAPIresult {
// thumbnail url
var thumbnail : String?
// book title
var title : String?
// book author
var author : String?
// book pub.
var pubnm : String?
// book description
var description : String?
// sellerID
var seller : String?
// list Price
var listPrice : String?
// selling Price
var sellPrice : String?
// UIImage for Thumbnail
var thumbnailImage : UIImage?
}
and SearchHome class is below. 并且SearchHome类在下面。
class SearchHome: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate{
// MARK: - Properties
let searchController = UISearchController(searchResultsController: nil)
// var barButton = UIBarButtonItem(title: "Search", style: .Plain, target: nil, action: nil)
let apiKey : String = "cbccaa3f2e893c245785c3b94d980b0c"
var searchString : String = ""
var list = Array<BookAPIresult>()
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.searchController.delegate = self
//self.searchController.searchBar.text! = ""
//Setup the status bar
tableView.contentInset.top = 0
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
searchController.searchBar.sizeToFit()
self.definesPresentationContext = true
self.tableView.tableHeaderView = searchController.searchBar
//searchController.navigationItem.rightBarButtonItem = barButton
searchController.hidesNavigationBarDuringPresentation = true
// Setup the Scope Bar
searchController.searchBar.scopeButtonTitles = ["Title", "HashTag"]
//tableView.tableHeaderView = searchController.searchBar
// Setup Animation for NavigationBar
navigationController?.hidesBarsOnSwipe = true
searchController.hidesNavigationBarDuringPresentation = false
navigationController?.hidesBarsWhenKeyboardAppears = false
navigationController?.hidesBarsOnTap = true
navigationController?.hidesBarsWhenVerticallyCompact = true
self.refreshControl?.addTarget(self, action: #selector(SearchHome.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
// declare hide keyboard swipe
let hideSwipe = UISwipeGestureRecognizer(target: self, action: #selector(SearchHome.hideKeyboardSwipe(_:)))
self.view.addGestureRecognizer(hideSwipe)
// searchController.searchBar.text = searchString
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
self.searchString = self.searchController.searchBar.text!
self.list.removeAll()
self.callBookAPI()
self.tableView.reloadData()
self.searchController.active = false
}
override func viewDidAppear(animated: Bool) {
self.searchController.active = false
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = self.list[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! BookAPIResultCell
cell.title?.text = row.title
cell.author?.text = row.author
dispatch_async(dispatch_get_main_queue(),{ cell.thumb.image = self.getThumbnailImage(indexPath.row)})
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
NSLog("%d 행을 눌렀음",indexPath.row)
var bookInfo = BookAPIresult()
let row = self.list[indexPath.row]
bookInfo.title = row.title
bookInfo.author = row.author
bookInfo.thumbnail = row.thumbnail
bookInfo.pubnm = row.pubnm
bookInfo.listPrice = row.listPrice
bookInfo.sellPrice = ""
bookInfo.seller = "nobody"
bookInfo.description = row.description
//detailVeiw instance
let postInfo = self.storyboard?.instantiateViewControllerWithIdentifier("detailBook") as! detailBook
postInfo.navigationItem.title = bookInfo.title
postInfo.bookDetail.append(bookInfo)
self.navigationController?.pushViewController(postInfo, animated: true)
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.view.endEditing(false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func callBookAPI(){
let encodedSearchString = searchString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let apiURI = NSURL(string: "https://apis.daum.net/search/book?apikey=\(self.apiKey)&q=\(encodedSearchString!)&searchType=title&output=json")
let apidata : NSData? = NSData(contentsOfURL: apiURI!)
NSLog("API Result = %@", NSString(data: apidata!, encoding: NSUTF8StringEncoding)!)
do {
let data = try NSJSONSerialization.JSONObjectWithData(apidata!, options:[]) as! NSDictionary
let channel = data["channel"] as! NSDictionary
// NSLog("\(data)")
let result = channel["item"] as! NSArray
var book : BookAPIresult
for row in result {
book = BookAPIresult()
let title = row["title"] as? String
book.title = title
if let authorEx = row["author"] as? String{
book.author = authorEx
}else{
book.author = ""
}
if let pubEX = row["pub_nm"] as? String{
book.pubnm = pubEX
}else{
book.pubnm = ""
}
if let listEX = row["list_price"] as? String{
book.listPrice = "\(listEX)dollar"
}else{
book.listPrice = "0"
}
if let thunmbEX = row["cover_s_url"] as? String{
book.thumbnail = thunmbEX
}else{
book.thumbnail = ""
}
//NSLog("\(book.thumbnail)")
if let description = row["description"] as? String{
if let decodedDescription = description.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding){
book.description = decodedDescription
}else{
book.description = ""
}
}else{
book.description = ""
}
self.list.append(book)
}
} catch {
NSLog("parse error")
}
}
func getThumbnailImage(index : Int) -> UIImage {
let book = self.list[index]
if let savedImage = book.thumbnailImage {
return savedImage
} else {
if book.thumbnail == "" {
book.thumbnailImage = UIImage(named:
"Book Shelf-48.png")
}else{
let url = NSURL(string: book.thumbnail!)
let imageData = NSData(contentsOfURL: url!)
book.thumbnailImage = UIImage(data:imageData!)
}
return book.thumbnailImage!
}
}
func handleRefresh(refreshControl:UIRefreshControl){
self.searchString = self.searchController.searchBar.text!
self.list.removeAll()
self.callBookAPI()
self.tableView.reloadData()
refreshControl.endRefreshing()
}
override func prefersStatusBarHidden() -> Bool {
return false
}
}
extension SearchHome: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
// filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
}
And the last is detailBook. 最后是detailBook。
class detailBook : UITableViewController {
var bookDetail = Array<BookAPIresult>()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.navigationController?.hidesBarsOnTap = false
self.navigationController?.hidesBarsWhenVerticallyCompact = false
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.navigationBarHidden = false
self.navigationItem.hidesBackButton = true
let backBtn = UIBarButtonItem(title: "뒤로가기", style: .Plain, target: self, action: "back:")
self.navigationItem.leftBarButtonItem = backBtn
//swipe to back
let backSwipe = UISwipeGestureRecognizer(target: self, action: "back:")
backSwipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(backSwipe)
//dynamic cell height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 620
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//define cell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! detailBookCell
let row = self.bookDetail[indexPath.row]
cell.author.text = row.author
cell.pubnm.text = row.pubnm
cell.listPrice.text = row.listPrice
cell.sellPrice.text = row.sellPrice
cell.detailInfo.text = row.description
cell.detailInfo.sizeToFit()
let url = NSURL(string: row.thumbnail!)
let imageData = NSData(contentsOfURL: url!)
cell.bookImage.image = UIImage(data:imageData!)
return cell
}
//back button
func back(recognizer: UISwipeGestureRecognizer){
self.navigationController?.popViewControllerAnimated(true)
bookDetail.removeAll()
}
}
You array, bookDetail, in the detailBlock class is still nil, so appending will not add any elements. 您在detailBlock类中的bookDetail数组仍然为nil,因此追加将不会添加任何元素。 You should first initialize a new array, add your bookInfo item to it, then assign detailBook's bookDetail item to this new array.
您应该首先初始化一个新数组,向其中添加bookInfo项,然后将detailBook的bookDetail项分配给该新数组。
You'll need to use the prepareForSegue method in your search view controller and then use performSequeWithIdentifier in your didSelectRowAtIndexPath. 您需要在搜索视图控制器中使用prepareForSegue方法,然后在didSelectRowAtIndexPath中使用performSequeWithIdentifier。
Basically, set up a placeholder object in the bookDetail view controller. 基本上,在bookDetail视图控制器中设置一个占位符对象。 In the search view controller set the value of a global object based in didSelecRowAtIndexPath and use the prepareForSegue method to set the placeholder object with the one you just set on your search view controller.
在搜索视图控制器中,基于didSelecRowAtIndexPath设置全局对象的值,并使用prepareForSegue方法将占位符对象设置为您刚刚在搜索视图控制器上设置的占位符。 When you select a row and it calls the performSegueWithIdentifier method, it will automatically call prepareForSegue and pass the value to the new view controller.
选择一行并调用performSegueWithIdentifier方法时,它将自动调用prepareForSegue并将值传递给新的视图控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.