2016-08-16 14 views
0

ユーザーが検索すると、最初の表のビュー(searchHome)に結果が表示されます。
1つのセルを選択すると、次のtableView(bookDetail)にその詳細情報が表示されます。
bookDetailでは、instagramのように1つのセルしか存在しません(私のページでは多くの画像を見ることができますが、1つを選択します。どのようにinstagramのようにtableviewからtableviewにデータを渡すのですか? swift

ただし、searchHomeのデータはdetailBookに渡されません。

この問題では3つのクラスがあります。
1つのデータを渡すためのクラス(BookAPIResult)
別あり、他方はdetailIndoためのUITableViewControllerのクラス(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クラス下にある検索のためのUITableViewControllerのクラス(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) 
} 
} 

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

SearchHomeのpostInfo.bookDetail.append(bookInfo)の後、0値はdetailBookクラスのbookDetail(配列)にあります。 – kimpro

答えて

0

detailBlockクラスの配列bookDetailはまだnilなので、追加すると要素が追加されません。最初に新しい配列を初期化し、bookInfo項目を追加してから、この新しい配列にdetailBookのbookDetail項目を割り当てます。

+0

私はどのように初期化するかを教えていただけますか? – kimpro

+0

ストーリーボードからビューコントローラをインスタンス化した後に、DidSelectRowAtIndexPathに新しい配列を作成します。その後、bookInfoオブジェクトを追加して、この新しい配列に等しいpostInfo.bookDetailを割り当てます。しかし、なぜこのような状況で配列を使用しているのかと聞かれますか? BookApiオブジェクトのインスタンスを1つだけ渡しているようです。あなたは、あなたのdetailBookコントローラにbookAPIプロパティを持たせて、DidSelectRowAtIndexPathで作成したbookInfoにそれを割り当てることができます。 –

0

検索ビューコントローラでprepareForSegueメソッドを使用し、didSelectRowAtIndexPathでperformSequeWithIdentifierを使用する必要があります。

基本的には、bookDetailビューコントローラでプレースホルダオブジェクトを設定します。検索ビュー・コントローラでは、didSelecRowAtIndexPathに基づいてグローバル・オブジェクトの値を設定し、prepareForSegueメソッドを使用して、検索ビュー・コントローラで設定したプレースホルダ・オブジェクトを設定します。行を選択してperformSegueWithIdentifierメソッドを呼び出すと、自動的にprepareForSegueが呼び出され、その値が新しいView Controllerに渡されます。

+0

このソリューションはあなたのために機能しましたか? –

関連する問題