自定义 UI TableViewCell 选择的背景色 swift [英] Custom UI TableViewCell selected backgroundcolor swift

查看:67
本文介绍了自定义 UI TableViewCell 选择的背景色 swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Swift 更改自定义选定 TableViewCell 的外观.

I am trying to change the appearance of a custom selected TableViewCell using Swift.

我需要通过设计器还是通过编程来完成?

Do I need to do it via the designer or programmatically?

我尝试了以下方法:

这是我的代码:

@IBOutlet var tableView: UITableView!


    var tableData: [String] = ["One", "Two", "Three", "Four"]

    override func viewDidLoad() {
        super.viewDidLoad()


        // Register custom cell
        var nib = UINib(nibName: "vwTblCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")

    }

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

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

        var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TblCell

        cell.lblCarName.text = tableData[indexPath.row]
        cell.imgCarName.image = UIImage(named: tableData[indexPath.row])

        return cell

    }

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

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

推荐答案

您已经有了正确的方法:didSelectRowAtIndexPath.在该方法中,您可以调用 tableView.cellForRowAtIndexPath(indexPath) 并获取您的单元格.比您可以将单元格背景设置为您的颜色:

You've the right method already in there: didSelectRowAtIndexPath. In that method you can call tableView.cellForRowAtIndexPath(indexPath) and get your cell. Than you can set the cell-background to your color:

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
        let cell:YourCustomCell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
        cell.backgroundColor = UIColor.redColor()
    }

或者,如果选择了一个单元格,更好的方法是检查您的 cellForRowAtIndexPath 方法:

Or, a better way would be to check in your cellForRowAtIndexPath method, if a cell is selected:

if(cell.selected){
  cell.backgroundColor = UIColor.redColor()
}else{
  cell.backgroundColor = UIColor.clearColor()
}

这篇关于自定义 UI TableViewCell 选择的背景色 swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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