在表视图单元 iOS 中将值设置为 UILabel
Posted
技术标签:
【中文标题】在表视图单元 iOS 中将值设置为 UILabel【英文标题】:Setting values to UILabels in Table View cell iOS 【发布时间】:2016-01-07 01:01:16 【问题描述】:我是 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
【问题讨论】:
您需要设置您的cellForRowAtIndexPath
。看起来好像您使用的是香草UITableViewCell
,因此您需要TableViewController
上的插座才能通过cellForRowAtIndexPath
设置标签。
当我将三个出口添加到我的 searchviewcontroller.swift 文件时,我得到错误:非法配置:从 SearchViewController 到 UILabel 的 DrinkName 出口无效。插座不能连接到重复的内容。 @AdrianB
【参考方案1】:
UITableViews 在拉模型上工作,因此您需要将饮料存储到当前打印结果的视图控制器上的数组变量中。然后在表视图上调用 reloadData。要以类型安全的方式存储饮料,请创建一个具有名称和类别等属性的 Drink 模型类。然后在 numberOfRowsInSection 返回drinks.count 并在cellForRowAtIndexPath 中获取drinks[indexPath.row],您应该能够从中获取名称等,并使用它来填充tableviewcell 中的标签。获取图像更加复杂,因为您需要发出另一个网络请求,但是一旦您使文本正常工作,您将取得良好的进展。
【讨论】:
当我将三个出口添加到我的 searchviewcontroller.swift 文件时,我得到错误:非法配置:从 SearchViewController 到 UILabel 的 DrinkName 出口无效。插座不能连接到重复的内容。 @达拉斯约翰逊 首先尝试使用一个默认的 UITableviewCells,它是 cellForRowAtIndexPath 中的一个。然后,您可以只使用内置文本标签的文本,而不需要任何 uilabels 的出口。查看这里了解更多详情developer.apple.com/library/ios/documentation/UIKit/Reference/…以上是关于在表视图单元 iOS 中将值设置为 UILabel的主要内容,如果未能解决你的问题,请参考以下文章
根据 iOS SWIFT 高度更高的 UIImageView 或 UILabel 设置 UITableViewCell 高度