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

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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值