I am loading news from the server in to the tableView. Now I want to make a custom cell with headline, image and excerpt. I made a custom class for the cell and I gave the cell custom identifier. I put two labels (one for headline and one for excerpt). Now I just want to display headline in the first label and excerpt in the second label.
@IBOutlet weak var headline: UILabel!
@IBOutlet weak var excerpt: UILabel!
//Custom struct for the data
struct News {
let title : String
let text : String
let link : String
let imgUrl : String
init(dictionary: [String:String]) {
self.title = dictionary["title"] ?? ""
self.text = dictionary["text"] ?? ""
self.link = dictionary["link"] ?? ""
self.imgUrl = dictionary["imgUrl"] ?? ""
}
}
//Array which holds the news
var newsData = [News]()
// Download the news
func downloadData() {
Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
//Optional binding to handle exceptions
self.newsData.removeAll() // clean the data source array
if let json = response.result.value as? [[String:String]] {
for news in json {
self.newsData.append(News(dictionary: news))
}
self.tableView.reloadData()
}
}
}
And in the following method I display the data in the cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let news = newsData[indexPath.row]
cell.textLabel?.text = news.title
cell.detailTextLabel?.text = news.text
return cell
}
Create a subclass from UITableViewCell
fe NewsCell
.
connect your outlets
@IBOutlet weak var headline: UILabel!
@IBOutlet weak var excerpt: UILabel!
to NewsCell
. In your override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
function cast the cell like this:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NewsCell
and set your properties.
Make sure you set the class of the storyboard prototype cell as NewsCell.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.