2017-01-09 117 views
0

我从服务器中加载消息到tableView。现在我想用标题,图片和摘录制作一个自定义单元格。 我为这个单元做了一个自定义的类,并给出了这个单元格的自定义标识符。 我放了两个标签(一个标题和一个摘录)。 现在我只想在第一个标签中显示标题并在第二个标签中显示摘录。如何在Swift 3中填充tableView自定义单元格?

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

而在下面的方法我显示在细胞

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 
} 
+1

什么是您的自定义类的名称?你应该将Cell作为你的定制玩具,你将能够做你想做的! –

+1

例如我有一个表格视图单元格自定义类叫做NewsCell所以我做:cell = tableView.dequeueReusableCell(withIdentifier:“newsCell”)as? NewsCell –

+0

您能否提供更多信息?我应该在自定义类“newsCellTableViewCell”中添加这些标签吗? –

回答

0

数据从UITableViewCell F.E.创建子类NewsCell

连接您的网点

@IBOutlet weak var headline: UILabel! 
@IBOutlet weak var excerpt: UILabel! 

NewsCell。在您的override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

功能铸就细胞是这样的:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NewsCell 

,并设置你的属性。

确保您将故事板原型单元格的类设置为NewsCell。

相关问题