ios Swift UItableView 以编程方式自定义单元格(文档)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28999400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:10:09  来源:igfitidea点击:

Swift UItableView Custom cell programmatically (documentation)?

iosswiftuitableviewcocoa-touch

提问by MLyck

I've been trying to find some documentation/tutorial/examples. On how to do an advanced tableview in swift. But I've come up empty besides the endless storyboard tutorials.

我一直在寻找一些文档/教程/示例。关于如何在 swift 中进行高级 tableview。但除了无休止的故事板教程之外,我还没有找到。

I'm doing this without storyboards and nibs. And I haven't been able to find any documentation beyond's Apple's /poorly/ explained library.

我这样做没有故事板和笔尖。除了 Apple 的 /poorly/ 解释库之外,我还找不到任何文档。

Rather than trying to explain exactly what I'm looking for, I'll simply show an image of the design below.

与其试图准确地解释我在寻找什么,我将简单地展示下面的设计图像。

enter image description here

在此处输入图片说明

Right now, I'm obviously not asking you guys to create this for me. I'm simply hoping you can send me a link to some documentation/tutorial. That explains how to make cells different? and how you position elements within a cell programmatically.

现在,我显然不是要你们为我创造这个。我只是希望您能向我发送一些文档/教程的链接。这解释了如何使细胞与众不同?以及如何以编程方式在单元格中定位元素。

I've been searching for cell constraints, but I can't find any?

我一直在寻找单元格约束,但找不到?

I looked into prototype cells too, but all I could find was storyboard related.

我也研究了原型单元格,但我能找到的只是故事板相关的。

I'm hoping you guys could show me an example of something similar, some documentation / tutorial.

我希望你们能给我看一个类似的例子,一些文档/教程。

Another important thing. Any documentation I did find that wasn't using storyboards. All used a tableViewController.

另一个重要的事情。我发现的任何文档都没有使用故事板。都使用了一个 tableViewController。

I'm using a UIViewController, with a UITableView. Not a tableViewController, which seems to make a huge difference on how it works.

我正在使用 UIViewController 和 UITableView。不是 tableViewController,这似乎对它的工作方式产生了巨大的影响。

Right now I'm just trying to get a prototype working.

现在我只是想让一个原型工作。

here's my data below:

这是我的数据如下:

var objects = NSMutableArray()
var dataArray = [   ["stockName":"CTC Media Inc.","action":"sell","stockPrice":12.44],
                    ["stockName":"Transglobal Energy","action":"buy","stockPrice":39.40],
                    ["stockName":"NU Skin Enterprises","action":"buy","stockPrice":4.18]
                ]

I've only been able to grab and display one piece of data from it though.

不过,我只能从中获取并显示一条数据。

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //return self.stocks.count
    return dataArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
    let object = dataArray[indexPath.row] as NSDictionary
    cell.textLabel?.text = object["stockName"] as? String

    return cell

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println("You selected cell #\(indexPath.row)!")
}

But I'm still clueless on how I position this data, or add more to it. Such as the UIView on the right with a specific background color. Centering a UILabel within that UIView, adding a UIView on the left with padding, custom spacing between cells. Etc. etc.

但是我仍然对如何定位这些数据或添加更多数据一无所知。比如右边带有特定背景色的 UIView。将该 UIView 中的 UILabel 居中,在左侧添加一个 UIView,并在单元格之间填充自定义间距。等等等等。

Any help, links to documentation, suggestions would be greatly appreciated!

任何帮助、文档链接、建议将不胜感激!

EDIT:

编辑:

I tried adding constraints inside the cell with. "cell.view.addConstraints("

我尝试在单元格内添加约束。"cell.view.addConstraints("

But of course it throws an error saying "UITableViewCell does not have a member named view".

但当然它会抛出一个错误,说“UITableViewCell 没有名为 view 的成员”。

So as for how to do constraints inside cells, I'm still blank :(

所以至于如何在单元格内做约束,我还是空白:(

EDIT 2 - progress:

编辑 2 - 进展:

I managed to get a UIView to show up using the following code:

我设法使用以下代码显示 UIView:

        testView.setTranslatesAutoresizingMaskIntoConstraints(false)
    testView.backgroundColor = UIColor.redColor()
    cell.addSubview(testView)

    var viewsDictionary = [ "testView":testView]
    cell.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat(
            "H:|-50-[testView]|", options: nil, metrics: nil, views: viewsDictionary))
    cell.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat(
            "V:|[testView]|", options: nil, metrics: nil, views: viewsDictionary))

However, for some reason, it only shows up in the last cell, not all cells?

但是,由于某种原因,它只出现在最后一个单元格中,而不是所有单元格中?

回答by HMHero

enter image description here

在此处输入图片说明

I just played little bit. Even though all the colors/fonts are not quite right, this will give you good starting point. Hope it helps you.

我只是玩了一点。即使所有颜色/字体都不完全正确,这也将为您提供良好的起点。希望对你有帮助。

class Stock {
var name: String?
var action: String?
var price: String?
init(stockData: [String: AnyObject]) {
    if let n = stockData["stockName"] as? String {
        name = n
    }
    if let a = stockData["action"] as? String {
        action = a
    }
    if let p = stockData["stockPrice"] as? Float {
        price = NSString(format: "%.2f", p)
    }
}

var backgroundColor: UIColor {
    if action == "sell" {
        return UIColor.greenColor()
    }
    return UIColor.blueColor()
}

var typeColor: UIColor {
    if action == "sell" {
        return UIColor.blackColor()
    }
    return UIColor.purpleColor()
}

var priceLabelColor: UIColor {
    if action == "sell" {
        return UIColor.redColor()
    }
    return UIColor.greenColor()
}
}


class StockCell: UITableViewCell {

let padding: CGFloat = 5
var background: UIView!
var typeLabel: UILabel!
var nameLabel: UILabel!
var priceLabel: UILabel!

var stock: Stock? {
    didSet {
        if let s = stock {
            background.backgroundColor = s.backgroundColor
            priceLabel.text = s.price
            priceLabel.backgroundColor = s.priceLabelColor
            typeLabel.text = s.action
            typeLabel.backgroundColor = s.typeColor
            nameLabel.text = s.name
            setNeedsLayout()
        }
    }
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    backgroundColor = UIColor.clearColor()
    selectionStyle = .None

    background = UIView(frame: CGRectZero)
    background.alpha = 0.6
    contentView.addSubview(background)

    nameLabel = UILabel(frame: CGRectZero)
    nameLabel.textAlignment = .Left
    nameLabel.textColor = UIColor.blackColor()
    contentView.addSubview(nameLabel)

    typeLabel = UILabel(frame: CGRectZero)
    typeLabel.textAlignment = .Center
    typeLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(typeLabel)

    priceLabel = UILabel(frame: CGRectZero)
    priceLabel.textAlignment = .Center
    priceLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(priceLabel)
}

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

override func prepareForReuse() {
    super.prepareForReuse()

}

override func layoutSubviews() {
    super.layoutSubviews()
    background.frame = CGRectMake(0, padding, frame.width, frame.height - 2 * padding)
    typeLabel.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
    priceLabel.frame = CGRectMake(frame.width - 100, padding, 100, frame.height - 2 * padding)
    nameLabel.frame = CGRectMake(CGRectGetMaxX(typeLabel.frame) + 10, 0, frame.width - priceLabel.frame.width - (CGRectGetMaxX(typeLabel.frame) + 10), frame.height)
}
}

in your view controller

在您的视图控制器中

var stocks: [Stock] = []

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.whiteColor()

    for stockData in dataArray {
        var stock = Stock(stockData: stockData)
        stocks.append(stock)
    }


    tableView = UITableView(frame: view.bounds, style: .Grouped)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .None
    tableView.registerClass(StockCell.self, forCellReuseIdentifier: NSStringFromClass(StockCell))
    view.addSubview(tableView)
}



func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stocks.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier( NSStringFromClass(StockCell), forIndexPath: indexPath) as StockCell
    cell.stock = stocks[indexPath.row]
    return cell

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 70
}

Custom Cell

自定义单元格

class StockCell: UITableViewCell {

let padding: CGFloat = 5
var background: UIView!
var typeLabel: UILabel!
var nameLabel: UILabel!
var priceLabel: UILabel!

var stock: Stock? {
    didSet {
        if let s = stock {
            background.backgroundColor = s.backgroundColor
            priceLabel.text = s.price
            priceLabel.backgroundColor = s.priceLabelColor
            typeLabel.text = s.action
            typeLabel.backgroundColor = s.typeColor
            nameLabel.text = s.name
            setNeedsLayout()
        }
    }
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    backgroundColor = UIColor.clearColor()
    selectionStyle = .None

    background = UIView(frame: CGRectZero)
    background.alpha = 0.6
    contentView.addSubview(background)

    nameLabel = UILabel(frame: CGRectZero)
    nameLabel.textAlignment = .Left
    nameLabel.textColor = UIColor.blackColor()
    contentView.addSubview(nameLabel)

    typeLabel = UILabel(frame: CGRectZero)
    typeLabel.textAlignment = .Center
    typeLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(typeLabel)

    priceLabel = UILabel(frame: CGRectZero)
    priceLabel.textAlignment = .Center
    priceLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(priceLabel)
}

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

override func prepareForReuse() {
    super.prepareForReuse()

}

override func layoutSubviews() {
    super.layoutSubviews()
    background.frame = CGRectMake(0, padding, frame.width, frame.height - 2 * padding)
    typeLabel.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
    priceLabel.frame = CGRectMake(frame.width - 100, padding, 100, frame.height - 2 * padding)
    nameLabel.frame = CGRectMake(CGRectGetMaxX(typeLabel.frame) + 10, 0, frame.width - priceLabel.frame.width - (CGRectGetMaxX(typeLabel.frame) + 10), frame.height)
}
}