在表视图单元格iOS中将值设置为UILabel

时间:2016-01-07 01:01:16

标签: ios swift uilabel tableviewcell

我是Swift和iOS开发的新手,对于初学者的问题感到抱歉。我试图在我的表视图单元格中设置两个UILabel文本值和一个UIImageView。我的数据来自API www.thecocktaildb.com

我正在搜索并从搜索栏中检索数据,例如:http://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita

我不知道如何将这些值传递给UILabels / UIImageView。有人能指出我正确的方向吗?或者,如果我在故事板中错误地设置它。谢谢!

下面是我的SearchViewController,其中包含搜索栏,表格视图和表格视图单元格。

My Search View Controller in my storyboard

附上贝叶是我的SearchViewController.swift文件

class SearchViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var TableView: UITableView!
    @IBOutlet weak var SearchBar: UISearchBar!

    // search in progress or not
    var isSearching : Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        for subView in self.SearchBar.subviews
        {
            for subsubView in subView.subviews
            {

                if let textField = subsubView as? UITextField
                {
                    textField.attributedPlaceholder  = NSAttributedString(string: NSLocalizedString("Search", comment: ""))

                }
            }
        }

        // set search bar delegate
        self.SearchBar.delegate = self
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        if self.SearchBar.text!.isEmpty {

            // set searching false
            self.isSearching = false

        }else{

            // set searghing true
            self.isSearching = true

            let userSearchInput = self.SearchBar.text!.lowercaseString

            let newString = userSearchInput.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil)

            let postEndpoint: String = "http://www.thecocktaildb.com/api/json/v1/1/search.php?s=" + newString

            guard let url = NSURL(string: postEndpoint) else {
                print("Error: cannot create URL")
                return
            }

            let urlRequest = NSURLRequest(URL: url)
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)

            let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
                guard let responseData = data else {
                    print("Error: did not receive data")
                    return
                }
                guard error == nil else {
                    print("error calling GET on www.thecocktaildb.com")
                    print(error)
                    return
                }
                // parse the result as JSON, since that's what the API provides
                let post: NSDictionary
                do {
                    post = try NSJSONSerialization.JSONObjectWithData(responseData,
                        options: []) as! NSDictionary
                } catch  {
                    print("error trying to convert data to JSON")
                    return
                }

                var count = 1
                if let drinks = post["drinks"] as? [NSDictionary] {
                    for drink in drinks {
                        if let strDrink = drink["strDrink"] as? String {
                            print(String(count) + ". " + strDrink)
                            count++
                        }
                        if let strCategory = drink["strCategory"] as? String {
                            print("    Category: " + strCategory)
                        }
                        if let strDrinkThumb = drink["strDrinkThumb"] as? String {
                            print("    Thumbnail Image: " + strDrinkThumb)
                        }
                    }
                }

            })
            task.resume()

        }

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }

    // hide kwyboard when search button clicked
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        self.SearchBar.resignFirstResponder()
    }

    // hide keyboard when cancel button clicked
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        self.SearchBar.text = ""
        self.SearchBar.resignFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

我打印到控制台时获得的数据示例:

1. Margarita
    Category: Ordinary Drink
    Thumbnail Image: http://www.thecocktaildb.com/images/media/drink/wpxpvu1439905379.jpg
2. Margarita #2
    Category: Ordinary Drink
3. Blue Margarita
    Category: Ordinary Drink
    Thumbnail Image: http://www.thecocktaildb.com/images/media/drink/qtvvyq1439905913.jpg
4. Peach Margarita
    Category: Cocktail
5. Midori Margarita
    Category: Ordinary Drink
6. Golden Margarita
    Category: Cocktail
7. Purple Margarita
    Category: Ordinary Drink
8. Mansion Margarita
    Category: Ordinary Drink
9. JimPop's Margarita
    Category: Ordinary Drink
10. Catalina Margarita
    Category: Cocktail
11. Ultimate Margarita
    Category: Cocktail
12. Whitecap Margarita
    Category: Other/Unknown
    Thumbnail Image: http://www.thecocktaildb.com/images/media/drink/srpxxp1441209622.jpg
13. Frozen Margarita #1
    Category: Ordinary Drink
14. Frozen Margarita #2
    Category: Ordinary Drink
15. Top Shelf Margarita
    Category: Cocktail
16. BlackJack Margarita
    Category: Ordinary Drink
17. Strawberry Margarita
    Category: Ordinary Drink
    Thumbnail Image: http://www.thecocktaildb.com/images/media/drink/tqyrpw1439905311.jpg
18. Bartender's Margarita
    Category: Ordinary Drink
19. The Perfect Margarita #1
    Category: Cocktail
20. The Perfect Margarita #2
    Category: Cocktail
21. RumRunner's Easy Margarita
    Category: Cocktail
22. Hand-Shaken Margarita on the Rocks
    Category: Ordinary Drink
23. Ken and Kirsten's top shelf Margarita
    Category: Ordinary Drink

1 个答案:

答案 0 :(得分:0)

UITableViews适用于拉模型,因此您需要将饮料存储到当前打印结果的视图控制器上的数组变量中。然后在表视图上调用reloadData。要以类型安全的方式存储饮料,请创建一个名称和类别等的Drink模型类作为属性。然后在numberOfRowsInSection中返回drinks.count,并在cellForRowAtIndexPath中获取您应该能够从中获取名称等的drink [indexPath.row]并使用它来填充tableviewcell中的标签。获取图像更复杂,因为您需要再次发出网络请求,但是一旦文本正常工作,您就会取得良好的进展。