如果用户搜索,结果将出现在第一个表View(searchHome)上 如果我选择一个单元格,我可以看到下一个tableView(bookDetail)的详细信息 所以在bookDetail中,所以只有一个单元格像instagram一样存在。(就像instagram我的页面。在我的页面中我可以看到很多图片,但我选择了一个,我只能看到1张带有详细信息的图片。)
但是searchHome的数据没有传递给detailBook。
这个问题共有3个班级
一个是传递数据的类(BookAPIResult)
另一个是用于搜索的UITableViewController类(SearchHome)
另一个是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 :(得分:0)
你的数组,bookDetail,在detailBlock类中仍然是nil,所以追加不会添加任何元素。您应该首先初始化一个新数组,将bookInfo项添加到它,然后将detailBook的bookDetail项分配给这个新数组。
答案 1 :(得分:0)
您需要在搜索视图控制器中使用prepareForSegue方法,然后在didSelectRowAtIndexPath中使用performSequeWithIdentifier。
基本上,在bookDetail视图控制器中设置占位符对象。在搜索视图控制器中,设置基于didSelecRowAtIndexPath的全局对象的值,并使用prepareForSegue方法将占位符对象设置为您在搜索视图控制器上设置的占位符对象。当您选择一行并调用performSegueWithIdentifier方法时,它将自动调用prepareForSegue并将值传递给新的视图控制器。