使用 Swift 以编程方式自定义 UITableViewCell [英] Custom UITableViewCell programmatically using Swift

查看:38
本文介绍了使用 Swift 以编程方式自定义 UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试创建一个自定义的 UITableViewCell,但我在模拟器上看不到任何东西.你能帮我吗.

Hey all I am trying to create a custom UITableViewCell, but I see nothing on the simulator. Can you help me please.

只有当我 var labUserName = UILabel(frame: CGRectMake(0.0, 0.0, 130, 30));

但它与单元格重叠.我不明白,Auto Layout 应该知道每个单元格的首选大小/最小大小吗?

but it overlaps the cell. I don't understand, Auto Layout should know the preferred size/minimum size of each cell?

谢谢

import Foundation
import UIKit

class TableCellMessages: UITableViewCell {
    var imgUser     = UIImageView();
    var labUserName = UILabel();
    var labMessage  = UILabel();
    var labTime     = UILabel();


    override init(style: UITableViewCellStyle, reuseIdentifier: String) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        imgUser.layer.cornerRadius = imgUser.frame.size.width / 2;
        imgUser.clipsToBounds = true;



        contentView.addSubview(imgUser)
        contentView.addSubview(labUserName)
        contentView.addSubview(labMessage)
        contentView.addSubview(labTime)


        //Set layout
        var viewsDict = Dictionary <String, UIView>()
        viewsDict["image"] = imgUser;
        viewsDict["username"] = labUserName;
        viewsDict["message"] = labMessage;
        viewsDict["time"] = labTime;
        //Image

        //contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[image(100)]-'", options: nil, metrics: nil, views: viewsDict));
        //contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[image(100)]-|", options: nil, metrics: nil, views: viewsDict));
         contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[username]-[message]-|", options: nil, metrics: nil, views: viewsDict));
         contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[username]-|", options: nil, metrics: nil, views: viewsDict));
          contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[message]-|", options: nil, metrics: nil, views: viewsDict));

    }

    required init(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
    }

}

推荐答案

让我们做一些假设:

您有一个带有 Storyboard 的 iOS8 项目,其中包含一个 UITableViewController.它的 tableView 有一个独特的原型 UITableViewCell,带有自定义样式和标识符:cell".

You have an iOS8 project with a Storyboard that contains a single UITableViewController. Its tableView has a unique prototype UITableViewCell with custom style and identifier: "cell".

UITableViewController 将链接到 TableViewController 类,cell 将链接到 CustomTableViewCell 类.

The UITableViewController will be linked to Class TableViewController, the cell will be linked to Class CustomTableViewCell.

然后您将能够设置以下代码(针对 Swift 2 进行了更新):

You will then be able to set the following code (updated for Swift 2):

CustomTableViewCell.swift:

import UIKit

class CustomTableViewCell: UITableViewCell {

    let imgUser = UIImageView()
    let labUserName = UILabel()
    let labMessage = UILabel()
    let labTime = UILabel()

    override func awakeFromNib() {
        super.awakeFromNib()

        imgUser.backgroundColor = UIColor.blueColor()

        imgUser.translatesAutoresizingMaskIntoConstraints = false
        labUserName.translatesAutoresizingMaskIntoConstraints = false
        labMessage.translatesAutoresizingMaskIntoConstraints = false
        labTime.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(imgUser)
        contentView.addSubview(labUserName)
        contentView.addSubview(labMessage)
        contentView.addSubview(labTime)

        let viewsDict = [
            "image": imgUser,
            "username": labUserName,
            "message": labMessage,
            "labTime": labTime,
        ]

        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[image(10)]", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[labTime]-|", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[username]-[message]-|", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[username]-[image(10)]-|", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[message]-[labTime]-|", options: [], metrics: nil, views: viewsDict))
    }

}

TableViewController.swift:

import UIKit

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Auto-set the UITableViewCells height (requires iOS8+)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell

        cell.labUserName.text = "Name"
        cell.labMessage.text = "Message (indexPath.row)"
        cell.labTime.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)

        return cell
    }

}

<小时>

您会期待这样的显示(iPhone 横向):


You will expect a display like this (iPhone landscape):

这篇关于使用 Swift 以编程方式自定义 UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆