码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-07-27 18:59:58      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

第一种方法是直接写一个继承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!
    }

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/howlaa/article/details/47087497

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!