2016-08-16 64 views
0

如果用户搜索,结果会出现在第一个表格View(searchHome)上。
如果我选择了一个单元格,我可以在下一个tableView(bookDetail)上看到这个详细信息。
所以在bookDetail中,所以只有一个单元格存在,就像instagram一样(它就像我的页面一样,在我的页面中可以看到很多图片,但是我选择了一个,我只能看到一张详细信息的图片)。如何将数据从tableview传递到像instagram一样的tableview? swift

但是searchHome的数据没有传递给detailBook。

这个问题有3个类。
一个是通过数据(BookAPIResult)
另一个是类的UITableViewController的搜索(SearchHome)
另一种是类的UITableViewController的用于detailIndo(bookDetail)

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? 

} 

和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) 
} 
} 

而最后是详细的书。

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() 
} 
} 
+0

在SearchHome中的postInfo.bookDetail.append(bookInfo)之后,0值位于detailBook Class的bookDetail(Array)中。 – kimpro

回答

0

您在arrayBlock类中的数组bookDetail仍然为零,因此追加将不会添加任何元素。您应该首先初始化一个新数组,将您的bookInfo项目添加到它,然后将detailBook的bookDetail项目分配给这个新数组。

+0

你能告诉我怎么回答我在哪里初始化? – kimpro

+0

在从故事板实例化视图控制器后,您将在DidSelectRowAtIndexPath中创建一个新数组。然后将bookInfo对象添加到它,然后分配postInfo.bookDetail等于这个新的数组。但是,请问为什么在这种情况下使用数组?看起来你只传递了一个BookApi对象的实例。您可以在您的detailBook控制器上拥有一个bookAPI属性,并将其分配给您在DidSelectRowAtIndexPath中创建的bookInfo。 –

0

您需要在搜索视图控制器中使用prepareForSegue方法,然后在didSelectRowAtIndexPath中使用performSequeWithIdentifier。

基本上,在bookDetail视图控制器中设置一个占位符对象。在搜索视图控制器中,设置基于didSelecRowAtIndexPath的全局对象的值,并使用prepareForSegue方法来设置占位符对象,并使用您在搜索视图控制器上设置的占位符对象。当你选择一行并调用performSegueWithIdentifier方法时,它将自动调用prepareForSegue并将值传递给新的视图控制器。

+0

此解决方案适合您吗? –

相关问题