【问题标题】:Swift. Viewcontroller aware of Subclass迅速。 Viewcontroller 知道子类
【发布时间】:2017-04-07 00:16:34
【问题描述】:

我有一个表格视图单元格的子类。

class profileTableViewCell: UITableViewCell {

    @IBOutlet weak var tableviewUsernameLabel: UILabel!
    @IBOutlet weak var tableviewMessageLabel: UILabel!
    @IBOutlet weak var tableviewTimeStamp: UILabel!
}

我需要在我的视图控制器中访问这些标签。我该怎么做。我对编程相当陌生。

-我在下面的标签上明显看到“未解析的标识符”。如何访问这些标签?

-还尝试将 cell.tableViewUsername.text (cell.) 放在所有标签的前面仍然不起作用。

class UserProfile: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = profileTableView.dequeueReusableCell(withIdentifier: "profileCell")


        //Set username label to display username
        let usernameLabel = cell?.viewWithTag(1) as! UILabel
        tableviewUsernameLabel.text = profileDataArray[indexPath.row].username


        //Set message label to display message
        let messageLabel = cell?.viewWithTag(2) as! UILabel
        tableviewMessageLabel.text = profileDataArray[indexPath.row].message
        tableviewMessageLabel.numberOfLines = 0



        //Set timeStampLabel to current time AGO
        let timeStampLabel = cell?.viewWithTag(4) as! UILabel
        tableviewTimeStamp.text = profileDataArray[indexPath.row].timeStamp
        tableviewTimeStamp.numberOfLines = 0



        return cell!
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return profileDataArray.count // your number of cell here
    }


}

【问题讨论】:

  • 你应该得到一些额外的功劳,因为你想出了 viewWithTag 来解决你的问题 ;-) 但下面的答案提供了标准的成语。

标签: ios swift uitableview casting


【解决方案1】:

你必须type castdequeueReusableCell(withIdentifier:)返回的单元格到profileTableViewCell

let cell = profileTableView.dequeueReusableCell(withIdentifier: "profileCell") as! profileTableViewCell

cell.tableviewUsernameLabel.text = ...
cell.tableviewMessageLabel.text = ...
cell.tableviewTimeStamp.text = ...

return cell

【讨论】:

  • 顺便说一句,你真的应该按照标准的 Swift 命名约定将你的类命名为 ProfileTableViewCell
  • 你最好的!谢谢你。 ;)
猜你喜欢
  • 2019-04-07
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多