在iOS中通过tabbar按钮返回主视图(表视图)后的黑色窗口

时间:2016-08-10 08:18:38

标签: ios iphone swift

在Root视图中,我使用了Tabbar控制器,有4个选项卡 在第一个选项卡View(index = 0),用户可以在打开的Book API服务上搜索书籍。它运作良好,但这是一个问题 1.用户在第一个标签视图(index = 0,tableview)上搜索书籍 结果出来了 3.用户选项卡其他选项卡按钮并移动其他视图 4.用户选择第一个按钮(索引= 0,表格视图)以备份搜索其他书籍 5.黑色屏幕显示在第一个选项卡视图中,但用户可以通过点击其他选项卡移动到其他视图,没有黑屏。仅在第一个视图(index = 0)

中有黑屏

我的应用有什么问题? 我用swift编写了我的应用程序。

import Foundation
import UIKit

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 = "cbccaa3f----d980b0c"

var searchString : String = ""

var list = Array<BookAPIresult>()

  // MARK: - View Setup
override func viewDidLoad() {
    super.viewDidLoad()


    self.searchController.searchBar.text! = ""

    // Setup the Search Controller
    searchController.searchResultsUpdater = self
    searchController.searchBar.delegate = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
    searchController.searchBar.sizeToFit()     
    self.tableView.tableHeaderView = searchController.searchBar


    // Setup the Scope Bar
    searchController.searchBar.scopeButtonTitles = ["title", "hashtag"]
    searchController.searchBar.placeholder = "book search"

    // 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 tap
    let hideTap = UITapGestureRecognizer(target: self, action: #selector(SearchHome.hideKeyboardTap(_:)))
    hideTap.numberOfTapsRequired = 1
    self.view.userInteractionEnabled = true
    self.view.addGestureRecognizer(hideTap)

    // declare hide keyboard swipe
    let hideSwipe = UISwipeGestureRecognizer(target: self, action: #selector(SearchHome.hideKeyboardSwipe(_:)))
    self.view.addGestureRecognizer(hideSwipe)

}


    // MARK: - UISearchBar Delegate
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    //      filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar){

    self.searchString = self.searchController.searchBar.text!

    self.list.removeAll()

    self.callBookAPI()

    self.tableView.reloadData()

}

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]

    NSLog("title:\(row.title),row:\(indexPath.row), author:\(row.author)")


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



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


            let decodedTitle = title?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)


            let titleFromHTML = decodedTitle!.html2String

            let titleRemoveB = titleFromHTML
            let titleRemoveBEnd = titleRemoveB.stringByReplacingOccurrencesOfString("</b>", withString: "")
            book.title = titleRemoveBEnd

            if let authorEx = row["author"] as? String{
                book.author = authorEx
            }else{
                book.author = ""
            }

            book.thumbnail = row["cover_s_url"] as? String

            //NSLog("\(book.thumbnail)")
            let description = row["description"] as? String

            let decodedDescription = description?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
            book.description = decodedDescription!

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

// hide keyboard if tapped
func hideKeyboardTap(recognizer: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

// hide keyboard if swipe
func hideKeyboardSwipe(recognizer: UISwipeGestureRecognizer) {
    self.view.endEditing(true)
}

override func prefersStatusBarHidden() -> Bool {
    return false
}

}



extension String {

var html2AttributedString: NSAttributedString? {
    guard
        let data = dataUsingEncoding(NSUTF8StringEncoding)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
}
}
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)
}
}

0 个答案:

没有答案