[swift修改表格选中单元格cell的样式背景颜色]Swift修改表格选中单元格(Cell)的样式(背景色,文字颜色)

更新时间:2020-04-01    来源:背景特效    手机版     字体:

【www.bbyears.com--背景特效】

使用 tableView 时,默认选中单元格的背景颜色是灰色的,如下图:

原文:Swift - 修改表格选中单元格(Cell)的样式(背景色,文字颜色)

1,使用自定义的背景颜色

这时就需要自定义 UITableViewCell 选中时背景View,并设置其颜色

原文:Swift - 修改表格选中单元格(Cell)的样式(背景色,文字颜色)

import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView:UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //创建表视图
        self.tableView = UITableView()
        self.tableView!.frame = CGRectMake(0, 0, self.view.frame.width,
            self.view.frame.height)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //创建一个重用的单元格
        self.tableView!.registerClass(UITableViewCell.self,
            forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)
    }
    
    //在本例中,只有一个分区
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    //返回表格行数(也就是返回控件数)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    //创建各单元显示内容(创建参数indexPath指定的单元)
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        //为了提供表格显示性能,已创建完成的单元需重复使用
        let identify:String = "SwiftCell"
        //同一形式的单元格重复使用,在声明时已注册
        let cell = tableView.dequeueReusableCellWithIdentifier(identify,
            forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = "条目\(indexPath.row)"
        
        //选中背景修改成绿色
        cell.selectedBackgroundView = UIView()
        cell.selectedBackgroundView?.backgroundColor =
            UIColor(red: 135/255, green: 191/255, blue: 49/255, alpha: 1)
        return cell
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

2,改变选中单元格的文字颜色

通过 cell 内文本标签的 textColor 和 highlightedTextColor 属性,可以分别设置文字默认颜色和选中颜色。


//默认文字颜色是黑色,选中项文字是白色
cell.textLabel?.textColor = UIColor.blackColor()
cell.textLabel?.highlightedTextColor = UIColor.whiteColor()

本文来源:http://www.bbyears.com/wangyetexiao/91236.html

热门标签

更多>>

本类排行