您的位置:首页 > 移动开发 > IOS开发

IOS开发单元格自定义方法之一

2015-07-27 17:01 309 查看
第一种方法是直接写一个继承UITableViewCell。然后动态的添加子视图方式

具体步骤:

1.新建立一个cell类,继承UITableViewCell

2.在这个类里面,定义属性,比如UILabel

3.重载构造函数,把子视图添加上

4.可以使用这个类了。

CityCellTableViewCell类:

//
//  CityCellTableViewCell.swift
//  UITableViewDemo0
//
//  Created by 王丰 on 7/27/15.
//  Copyright (c) 2015 wangfeng. All rights reserved.
//

import UIKit

class CityCellTableViewCell: UITableViewCell {

    var cityLabel:UILabel?
    var cityTextFiled:UITextField?
    var citySwitch:UISwitch?
    
    
    override init(style: UITableViewCellStyle,reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //初始化子视图,子控件,然后添加到当前视图
        cityLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 80, height: 40))
        cityTextFiled = UITextField(frame: CGRect(x: 90, y: 5, width: 80, height: 40))
        citySwitch = UISwitch(frame: CGRect(x: 200, y: 5, width: 80, height: 40))
        //添加到当前视图
        self.addSubview(cityLabel!)
        self.addSubview(cityTextFiled!)
        self.addSubview(citySwitch!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


viewController重载tableView方法:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var cellId = "mycell"
        var cell:CityCellTableViewCell? = (tableView.dequeueReusableCellWithIdentifier(cellId) as? CityCellTableViewCell)
        
        if(cell == nil){
             cell = CityCellTableViewCell(style: UITableViewCellStyle.Subtitle,
                reuseIdentifier: cellId)
        }
        cell?.cityLabel?.text = cities[indexPath.row]
        cell?.cityTextFiled?.placeholder = "input number"
        cell?.citySwitch?.on = true
        return cell!
    }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: