簡體   English   中英

如何將數據從tableview傳遞到像instagram一樣的tableview? 迅速

[英]how to pass data from tableview to tableview like instagram? swift

如果用戶搜索,結果將顯示在第一個表View(searchHome)上。
如果選擇一個單元格,則可以在下一個tableView(bookDetail)上看到其詳細信息。
因此,在bookDetail中,只有一個像instagram這樣的單元格存在。(就像instagram我的頁面。在我的頁面中,我可以看到很多圖片,但是我選擇了一張,就只能顯示1張帶有詳細信息的圖片)。

但是searchHome的數據不會傳遞到detailBook。

這個問題有3個班級。
一種是用於傳遞數據的類(BookAPIResult)
另一個是用於搜索的UITableViewController類(SearchHome)
另一個是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?

} 

並且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()
}
}

您在detailBlock類中的bookDetail數組仍然為nil,因此追加將不會添加任何元素。 您應該首先初始化一個新數組,向其中添加bookInfo項,然后將detailBook的bookDetail項分配給該新數組。

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

基本上,在bookDetail視圖控制器中設置一個占位符對象。 在搜索視圖控制器中,基於didSelecRowAtIndexPath設置全局對象的值,並使用prepareForSegue方法將占位符對象設置為您剛剛在搜索視圖控制器上設置的占位符。 選擇一行並調用performSegueWithIdentifier方法時,它將自動調用prepareForSegue並將值傳遞給新的視圖控制器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM