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

标签 ios swift uitableview cocoa-touch

我一直在努力寻找一些文档/教程/示例。关于如何在 swift 中做一个高级的 tableview。但除了没完没了的 Storyboard教程,我一无所获。

我在没有 Storyboard和 Nib 的情况下这样做。除了 Apple 的/poorly/explained 库之外,我还没有找到任何文档。

与其试图准确解释我正在寻找的内容,不如简单地展示下面的设计图片。

enter image description here

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

我一直在搜索单元格约束,但找不到任何内容?

我也研究了原型(prototype)单元,但我能找到的都是 Storyboard相关的东西。

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

还有一点很重要。我发现的所有未使用 Storyboard的文档。都使用了一个 tableViewController。

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

现在我只是想让原型(prototype)工作。

下面是我的数据:

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]
                ]

虽然我只能从中获取并显示一条数据。

    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)!")
}

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

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

编辑:

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

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

至于如何在单元格内部做约束,我还是一头雾水:(

编辑 2 - 进度:

我设法使用以下代码显示一个 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))

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

最佳答案

enter image description here

我只是玩了一点。尽管所有的颜色/字体都不是很正确,但这会给你一个很好的起点。希望对你有帮助。

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

在你的 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
}

自定义单元格

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

关于ios - Swift UItableView 以编程方式自定义单元格(文档)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28999400/

相关文章:

ios - 从 iOS 上的两个不同应用程序访问相同的文件

swift - 如何从 Swift 类引用 Objective C AppDelegate?

iphone - NSFetchRequest/谓词问题

swift - 自定义 tableviewcell 中的 PieChartView

ios - 更改标签栏导航 Controller 的根 Controller

ios - 如何在应用程序的每个页面上显示用户名,从登录页面的文本字段中获取用户名?

json - 如何快速将所有电话联系人传递给 JSON API

ios - 从 UITableViewController 的 View 模型呈现模态

iOS 按钮动画,如邮件应用程序

ios - 如何将 imageData 保存到 NSManagedObject 属性