Swift UItableView自定义单元格编程(文档)? [英] Swift UItableView Custom cell programatically (documentation)?

查看:199
本文介绍了Swift UItableView自定义单元格编程(文档)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找到一些文档/教程/示例。关于如何在swift中做一个高级tableview。但是除了无尽的故事板教程之外,我还是空着。



我没有故事板和笔尖。我没有找到任何超出苹果/不好/解释图书馆的文档。



不是试图解释我正在寻找什么,





现在,我显然不是要求你们为我创建这个。我只是希望你可以给我一个链接到一些文档/教程。这解释了如何使细胞不同?



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



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



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



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



我使用一个UIViewController,一个UITableView。不是一个tableViewController,它似乎对它的工作原理有很大的不同。



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



下面是我的数据:

  var objects = NSMutableArray()
var dataArray = [[stockName:CTC Media Inc。,action:sell,stockPrice:12.44],
[stockName:Transglobal Energy ,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 cell#\(indexPath.row)!)
}

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



任何帮助,链接到文档,建议将非常感谢!



编辑: / p>

我试着在单元格中添加约束。 cell.view.addConstraints(



但是当然它会抛出一个错误,UITableViewCell没有成员命名的视图。



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



EDIT 2 - progress:



我设法使用以下代码显示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 $ b NSLayoutConstraint.constraintsWithVisualFormat(
V:| [testView] |,options:nil,metrics:nil,views:viewsDictionary))

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

解决方案

>



我只是打了一点。即使所有的颜色/字体不是很对,这将给你一个很好的起点。希望它帮助你。

 类库{
var name:String?
var action:String?
var price:String?
init(stockData:[String:AnyObject]){
如果让n = stockData [stockName] as? String {
name = n
}
如果let a = stockData [action] as? String {
action = a
}
如果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 {
如果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()
}
}
}

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

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

在您的视图控制器中

  var stocks:[Stock] = [] 

override func viewDidLoad(){
super.viewDidLoad()

view.backgroundColor = UIColor.whiteColor()

for 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 {
如果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()
}
}
}

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

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


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.

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

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

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 programatically.

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.

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

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.

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

EDIT:

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

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

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

EDIT 2 - progress:

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

        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?

解决方案

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

这篇关于Swift UItableView自定义单元格编程(文档)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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