iOS Swift:正确初始化TableViewCell

时间:2017-02-07 20:41:30

标签: ios iphone uitableview swift3 tableviewcell

为了学习关于iOS开发的绳索;我正在尝试使用各种类似Facebook的“帖子”创建一个tableview。对于这个问题,我将参考下面的XIB可见的“Photo Post”:

PhotoPostTableViewCell.xib:

enter image description here

class PhotoPostTableViewCell: UITableViewCell {
    @IBOutlet weak var postingUserImageButton: UIButton!
    @IBOutlet weak var postingUserNameButton: UIButton!
    @IBOutlet weak var timeStampLabel: UILabel!
    @IBOutlet weak var primaryImageView: UIImageView!
    @IBOutlet weak var postContentsLabel: UILabel!
    @IBOutlet weak var rippleLikesLabel: UILabel!
    @IBOutlet weak var rippleButton: UIButton!

    @IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
    ...
}

此帖子必需具有以下内容:

类型postingUserID

Int引用自定义用户类来链接用户图像和用户名(左上角)

类型photo

UIImage来保留帖子的主要图片

类型为postTimeStamp

String来捕获帖子发布的时间

类型为rippleLikes

Int,用于保存帖子中“喜欢”的数量;这将初始化为0

类型为postID

Int,以便此帖可在其他地方引用

这篇文章还有可选 String名为postContentLabel

我尝试了各种不同的方法,但似乎总是出现错误,所以我想我会寻求一些建议。

我的问题如下:

从相应的tableview委托方法中定义此类并创建/初始化此表视图单元类的最专业/最有效的方法是什么

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

1 个答案:

答案 0 :(得分:1)

我喜欢有一个属性来存储单元格所代表的实体。

class PhotoPostTableViewCell: UITableViewCell {

    // MARK: Outlets

    @IBOutlet weak var postContentLabel: UILabel?
    @IBOutlet weak var postPhotoImageView: UIImageView?
    @IBOutlet weak var postTimestampLabel: UILabel?
    @IBOutlet weak var rippleLikesLabel: UILabel?
    @IBOutlet weak var userImageView: UIImageView?
    @IBOutlet weak var userNameLabel: UILabel?

    // MARK: Properties

    var photoPost: PhotoPost? {
        didSet {
            // configure your outlets here
            // e.g. postContentLabel.text = photoPost?.content
        }
    }
}

您可以将插座配置代码从cellForItemAtIndexPath移动到单元格本身,只需设置单元格的photoPost属性。

override func viewDidLoad() {

    super.viewDidLoad()

    tableView.register(UINib(nibName: "PhotoPostTableViewCell", bundle: nil), forCellReuseIdentifier: "PhotoPostCell")
}

...

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoPostCell", for: indexPath) as! PhotoPostTableViewCell

    cell.photoPost = photoPosts[indexPath.row]

    return cell
}

您的照片发布课程可能如下所示:

class PhotoPost {

    // MARK: Properties

    var contents: String?
    var id: Int!
    var photo: UIImage!
    var rippleLikes: Int!
    var timestamp: Double!
    var userID: Int!

    init(json: [String: Any]) {

        self.contents = json["contents"] as? String
        self.id = json["id"] as? Int
        self.photo = ...
        self.rippleLikes = json["rippleLikes"] as? Int
        self.timestamp = json["timestamp"] as? Double
        self.userID = json["userID"] as? Int
    }
}
相关问题