swift 代码笔记3

这篇博客介绍了如何在Swift中自定义UITableViewCell,包括在系统cell上添加UILabel和UIButton,以及使用富文本展示不同字体大小的文本。同时展示了如何创建不同样式的UITableViewCells,包括设置开关、按钮和不同类型的 accessoryView。此外,还涉及到根据需求动态调整cell内容的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1/   在系统的cell 中  可以自一个image view  覆盖到系统的 UIImageview   也可以在系统的 UIImageview  添加一个 UILable 或者 UIButton 的子控件 

 //var imgRili = UIImageView(frame: CGRectMake(0, 0, 0, 0))

        var lblrili = UILabel(frame: CGRectMake(2, 0, 30, 40))

        lblrili.font = UIFont.systemFontOfSize(12)

        lblrili.textColor = appThemeColor

        lblrili.text = "Aug"

        lblrili.textAlignment = NSTextAlignment.Center

        cell.imageView?.image = UIImage(named: "pouer_rili")

        cell.imageView?.addSubview(lblrili)

        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

        return cell



2/  富文本的使用 

(1) 

        var str1 = "2.1"

        var str2 : NSMutableAttributedString = NSMutableAttributedString(string:str1 + "kwh")

        let smallFont = [NSFontAttributeName:UIFont.systemFontOfSize(24)]

        let bigFont = [NSFontAttributeName:UIFont.systemFontOfSize(50)]

        str2.addAttributes(bigFont, range: NSMakeRange(0,(str1 as NSString).length))

        str2.addAttributes(smallFont, range: NSMakeRange((str1 as NSString).length,3))

        let headerTitle = UILabel(frame: CGRectMake(ScreenWidth/2,50,ScreenWidth/2,210-100))


        headerTitle.attributedText = str2

        headerView.addSubview(headerTitle)

(2)

        var strtmp = NSMutableAttributedString(string:"I agree Software License Agreement")

        let strRange = NSMakeRange(8,26)

        let addrAttr = [NSForegroundColorAttributeName:appThemeColor]

        strtmp.addAttributes(addrAttr, range: strRange)

        //strtmp.addAttribute(kCTForegroundColorAttributeName, value:appThemeColor.CGColor, range: strRange)

        let lblagree = UILabel(frame:CGRect(origin: CGPointMake(16, CGRectGetMaxY(txtPwd2.frame)+16), size: CGSize(width: self.view.frame.size.width-32, height: 14)))

        //lblagree.text = "I agree Software License Agreement"

        lblagree.attributedText = strtmp



3/  多种样式的tableviewcell 



import UIKit


class TTSmartModeViewController: UIViewController,TTInterceptorProtocol,UITableViewDataSource,UITableViewDelegate {


    enum SmartModeCellType:Int {

        case AutoPowerCellType = 1

        case AutoSleepCellType

        case TimerCellType

        case IndicatorCellType

        case LightOFFCellType

        case LightONCellType

        case LightAutoCellType

        case LightColorCellType

        

        var title:String{

            switch self {

            case AutoPowerCellType :

                return "Auto Power-on"

            case AutoSleepCellType:

                return "Auto Sleep Mode"

            case TimerCellType:

                return "Timer"

            case IndicatorCellType:

                return "Indicator Light"

            case LightOFFCellType:

                return "OFF"

            case LightONCellType:

                return "ON"

            case LightAutoCellType:

                return "Auto"

            case LightColorCellType:

                return "Light Color"

            default :

                return ""

            }

        }

        

        var image:UIImage? {

            switch self {

            case AutoPowerCellType :

                return UIImage(named: "smartmodel_autopower")

            case AutoSleepCellType:

                return UIImage(named: "smartmodel_autosleep")

            case TimerCellType:

                return UIImage(named: "smartmodel_time")

            case IndicatorCellType:

                return UIImage(named: "smartmodel_indicator")

            case LightOFFCellType,LightONCellType,LightAutoCellType:

                return UIImage.colorImage(UIColor.whiteColor(), size: CGSizeMake(60, 44))

            case LightColorCellType:

                return UIImage(named: "smartmodel_lightclolor")

            default :

                return UIImage(named: "")

            }

        }

        

        init(){

            self = AutoPowerCellType

        }

        

        func cellStyle(cell: UITableViewCell!, superViewController: TTSmartModeViewController,isShowLightType:Bool) {

            cell.accessoryView = nil

            switch self {

            case AutoPowerCellType :

                let powerSwitch = UISwitch(frame: CGRectMake(0, 0, 20, 10))

                powerSwitch.addTarget(superViewController, action: "switchAction:", forControlEvents: UIControlEvents.EditingChanged)

                powerSwitch.onTintColor = appThemeColor

                powerSwitch.tag = 1001

                cell.selectionStyle = UITableViewCellSelectionStyle.None

                cell?.accessoryView = powerSwitch

            case AutoSleepCellType:

                let sleepSwitch = UISwitch(frame: CGRectMake(0, 0, 20, 10))

                sleepSwitch.addTarget(superViewController, action: "switchAction:", forControlEvents: UIControlEvents.EditingChanged)

                sleepSwitch.onTintColor = appThemeColor

                sleepSwitch.tag = 1002

                cell.selectionStyle = UITableViewCellSelectionStyle.None

                cell?.accessoryView = sleepSwitch

            case TimerCellType:

                let timeButon = UIButton(frame: CGRectMake(0, 0,10, cell.frame.size.height))

                timeButon.userInteractionEnabled = false

                timeButon.setImage(UIImage(named:"smartmodel_nextBlue"), forState: UIControlState.Normal)

                cell?.accessoryView = timeButon

            case IndicatorCellType:

                let lightButon = UIButton(frame: CGRectMake(0, 0, isShowLightType == false ? 80 : 100, cell.frame.size.height))

                lightButon.userInteractionEnabled = false

                lightButon.titleLabel?.font = UIFont.systemFontOfSize(14)

                lightButon.setTitle("Auto", forState: UIControlState.Normal)

                lightButon.imageEdgeInsets = UIEdgeInsetsMake(0, isShowLightType == false ? 70 : 85, 0, 0)

                lightButon.setImage(UIImage(named: (isShowLightType == false ? "smartmodel_nextBlue" : "smartmodel_downBlue")), forState: UIControlState.Normal)

                lightButon.setTitleColor(appThemeColor, forState: UIControlState.Normal)

                cell?.accessoryView = lightButon

            case LightOFFCellType,LightONCellType,LightAutoCellType:

                cell.selectionStyle = UITableViewCellSelectionStyle.None

            case LightColorCellType:

                let colorButon = UIButton(frame: CGRectMake(0, 0, 80, cell.frame.size.height))

                colorButon.userInteractionEnabled = false

                colorButon.titleLabel?.font = UIFont.systemFontOfSize(14)

                colorButon.setTitle("Blue", forState: UIControlState.Normal)

                colorButon.imageEdgeInsets = UIEdgeInsetsMake(0, 70, 0, 0)

                colorButon.setImage(UIImage(named: "smartmodel_nextBlue"), forState: UIControlState.Normal)

                colorButon.setTitleColor(appThemeColor, forState: UIControlState.Normal)

                cell?.accessoryView = colorButon

            default :

                cell.selectionStyle = UITableViewCellSelectionStyle.Default

            }

             cell.imageView?.image = self.image

        }

    }

    

    var tableView: UITableView!

    var reserveBalanceData: [[SmartModeCellType]]!

    var tableViewCellHeight: CGFloat = 44.0

    var isShowLightType:Bool = false

    var selectIndex = 2

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.reserveBalanceData = [[.AutoPowerCellType],[.AutoSleepCellType],[.TimerCellType,.IndicatorCellType,.LightColorCellType]]

        self.setupUI()

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    //MARK:- Delegate or DataSource

    //MARK:- UITableViewDelegate & UITableViewDataSource

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return self.reserveBalanceData.count

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.reserveBalanceData[section].count

    }

    

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

        return tableViewCellHeight

    }


    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 0.1

    }

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {

        return 44.0

    }

    

    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

        if let type = self.reserveBalanceData[section].first where (type == .AutoPowerCellType || type == .AutoSleepCellType){

            let titleLabel = UILabel(frame: CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height))

            titleLabel.userInteractionEnabled = true

            titleLabel.font = UIFont.systemFontOfSize(12)

            titleLabel.textColor = defaultGrayColor

            titleLabel.text = section == 0 ? "    Open,provide comfort and comfort for you." : "   Open,help you enjoy a beautiful dream."

            let detailBurron = UIButton(frame: CGRectMake(titleLabel.frame.size.width - 50, 0, 40, titleLabel.frame.size.height))

            detailBurron.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin

            detailBurron.setTitle("Details", forState: UIControlState.Normal)

            detailBurron.tag = 88 + section

            detailBurron.addTarget(self, action: "detailAction:", forControlEvents: UIControlEvents.TouchUpInside)

            detailBurron.titleLabel?.font = UIFont.systemFontOfSize(12)

            detailBurron.setTitleColor(appThemeColor, forState: UIControlState.Normal)

            titleLabel.addSubview(detailBurron)

            return titleLabel

        }

        return nil

    }

    

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

        let cellIdentifier = "StarModelViewController_Cell"

        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell!

        if cell == nil {

            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier)

        }

        

        let settingType = self.reserveBalanceData[indexPath.section][indexPath.row]

        settingType.cellStyle(cell, superViewController: self, isShowLightType: self.isShowLightType)

        cell.textLabel?.text = settingType.title

        cell.textLabel?.textColor = tableViewCellDefaultTextColor

        

        if indexPath.row == self.selectIndex && self.isShowLightType{

           cell.accessoryType = UITableViewCellAccessoryType.Checkmark

        }else{

            cell.accessoryType = UITableViewCellAccessoryType.None

        }

        return cell

    }

    

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        switch indexPath.section {

        case 0:

            println("Auto Power-on")

        case 1:

            println("Auto Sleep Model")

        case 2:

            switch indexPath.row {

            case 0:

                var timerListVC = TTTimerListViewController()

                timerListVC.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(timerListVC, animated: true)

            case 1:

                self.isShowLightType = !self.isShowLightType

                self.reserveBalanceData.removeAtIndex(2)

                if !self.isShowLightType {

                    self.reserveBalanceData.append([.TimerCellType,.IndicatorCellType,.LightColorCellType])

                }else{

                    self.reserveBalanceData.append([.TimerCellType,.IndicatorCellType,.LightOFFCellType,.LightONCellType,.LightAutoCellType,.LightColorCellType])

                }

                self.tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Automatic)

            case 2:

                println("OFF")

                if !self.isShowLightType {

                    var colorvc = TTSetColorViewController()

                    colorvc.hidesBottomBarWhenPushed = true

                    self.navigationController?.pushViewController(colorvc, animated: true)

                } else {

                    self.setSelectCellForLight(indexPath)

                }

            case 3:

                println("ON")

                self.setSelectCellForLight(indexPath)

                

            case 4:

                println("Auto")

                self.setSelectCellForLight(indexPath)

                

            case 5:

                var colorvc = TTSetColorViewController()

                colorvc.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(colorvc, animated: true)

            default:

                println("didCell Error")

            }

        default:

            println("didCell Error")

        }

    }


    //MARK:- NSNotification Method

    

    //MARK:- Action Method

    

    func detailAction(sender:UIButton){

        switch sender.tag - 88 {

        case 0 :

            println("detali One")

            let faqvc = TTFaqTableViewController()

            faqvc.hidesBottomBarWhenPushed = true

            self.navigationController?.pushViewController(faqvc, animated: true)

        case 1 :

            println("detali Two")

            let faqvc = TTFaqTableViewController()

            faqvc.hidesBottomBarWhenPushed = true

            self.navigationController?.pushViewController(faqvc, animated: true)

        default:

            println("detail Error")

        }

    }

    //MARK:- Private Method

    private func setupUI(){

        // 列表

        self.view.autoresizesSubviews = true

        self.tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Grouped)

        self.view.addSubview(self.tableView)

        self.tableView.backgroundColor = defaultBackgroundGrayColor

        self.tableView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

        self.tableView.dataSource = self

        self.tableView.delegate = self

        self.tableView.tintColor = appThemeColor

        

    }

    //标记选择状态

    private func setSelectCellForLight(indexPath:NSIndexPath){

    

        let lastIndexPath = NSIndexPath(forRow: self.selectIndex, inSection: 2)

        let lastCell = self.tableView.cellForRowAtIndexPath(lastIndexPath)

        lastCell?.accessoryType = UITableViewCellAccessoryType.None

        

        let cell = self.tableView.cellForRowAtIndexPath(indexPath)

        cell?.accessoryType = UITableViewCellAccessoryType.Checkmark

        

        self.selectIndex = indexPath.row


    }

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值