Swift:表格视图单元格单选(一)

效果展示

这里写图片描述

前言

最近一个朋友问我,如何实现表格视图的单选?因为我之前用Objective-c写过一次,但那都是很久以前的事情了,于是就想着用swift实现一次,并分享给大家。

实现

下面我们来看看具体的实现方法。

首先我们创建一个Swift iOS工程,在AppDelegate.swift的didFinishLaunchingWithOptions 方法中手动初始化UIWindow,并且给根视图控制器添加导航栏,当然在此之前我们需要到Info.plist 文件中将Storyboard加载UIWindow字段的 Main 值删除。

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.backgroundColor = UIColor.blackColor()
self.window?.rootViewController = UINavigationController(rootViewController: ViewController())
self.window?.makeKeyAndVisible()

下一步,我们需要到ViewController.swift文件中搭建界面,构造表格视图,以及数据源的配置,这里我直接上代码,相信表格视图的使用大家已经非常熟悉了。代码中注册的单元格使用的是自定义的单元格,而处理单选的方法主要就是在自定义单元格 CustomTableViewCell 中实现,稍后我会提及,涉及到的素材可到阿里矢量图中下载。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView: UITableView?
    var dataSource: [String]?

    override func viewDidLoad() {
        super.viewDidLoad()


        self.initializeDatasource()
        self.initializeUserInterface()

    }

    // MARK:Initialize methods
    func initializeDatasource() {

        self.dataSource = ["中国", "美国", "法国", "德国"]
    }

    func initializeUserInterface() {
        self.title = "单项选择"
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()

        // initialize table view
        self.tableView = {
            let tableView = UITableView(frame: CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 64), style: UITableViewStyle.Grouped)
            tableView.dataSource = self
            tableView.delegate = self
            tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
            tableView.registerClass(CustomTableViewCell.classForCoder(), forCellReuseIdentifier: "cellIdentifier")
            return tableView
            }()
        self.view.addSubview(self.tableView!)
    }

    // MARK:UITableViewDataSource && UITableViewDelegate

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (self.dataSource?.count)!
    }

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

        let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) as! CustomTableViewCell

        cell.imageView?.image = UIImage(named: "iconfont-select.png")
        cell.textLabel?.text = self.dataSource![indexPath.row]

        return cell

    }


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

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "请选择您向往的城市:"
    }

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

        // get cell with index path
        let cell = tableView.cellForRowAtIndexPath(indexPath)

        print("您选择的城市:\((cell?.textLabel?.text)!)")
    }

}

接下来我们看看 CustomTableViewCell.swift 文件,在自定义单元格中,要做的操作非常简单,只需在 setSelected 方法中做如下操作即可:

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

        super.setSelected(selected, animated: animated)

        if selected {
            imageView?.image = UIImage(named: "iconfont-selected.png")
        }else {
            imageView?.image = UIImage(named: "iconfont-select.png")
        }
    }
}

好了,表格视图的单选就这样实现了,运行看看吧。可能在实际开发中会遇到更为复杂的情况,就是多个组的单选,比如你要做一个类似于习题库的应用,将会用到多个组的单选,那应该如何实现呢?可参考:表格视图单元格单选(二)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
接着分析 (result (type_ident (component id='Bool' bind=Swift.(file).Bool))) (brace_stmt range=[re.swift:1:59 - line:14:1] (pattern_binding_decl range=[re.swift:2:5 - line:2:33] (pattern_named type='[UInt8]' 'b') Original init: (call_expr type='[UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:33] nothrow (constructor_ref_call_expr type='(String.UTF8View) -> [UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:19] nothrow (declref_expr implicit type='(Array<UInt8>.Type) -> (String.UTF8View) -> Array<UInt8>' location=re.swift:2:19 range=[re.swift:2:19 - line:2:19] decl=Swift.(file).Array extension.init(_:) [with (substitution_map generic_signature=<Element, S where Element == S.Element, S : Sequence> (substitution Element -> UInt8) (substitution S -> String.UTF8View))] function_ref=single) (argument_list implicit (argument (type_expr type='[UInt8].Type' location=re.swift:2:13 range=[re.swift:2:13 - line:2:19] typerepr='[UInt8]')) )) (argument_list (argument (member_ref_expr type='String.UTF8View' location=re.swift:2:29 range=[re.swift:2:21 - line:2:29] decl=Swift.(file).String extension.utf8 (declref_expr type='String' location=re.swift:2:21 range=[re.swift:2:21 - line:2:21] decl=re.(file).check(_:_:).encoded@re.swift:1:14 function_ref=unapplied))) )) Processed init: (call_expr type='[UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:33] nothrow (constructor_ref_call_expr type='(String.UTF8View) -> [UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:19] nothrow (declref_expr implicit type='(Array<UInt8>.Type) -> (String.UTF8View) -> Array<UInt8>' location=re.swift:2:19 range=[re.swift:2:19 - line:2:19] decl=Swift.(file).Array extension.init(_:) [with (substitution_map generic_signature=<Element, S where Element == S.Element, S : Sequence> (substitution Element -> UInt8) (substitution S -> String.UTF8View))] function_ref=single) (argument_list implicit (argument (type_expr type='[UInt8].Type' location=re.swift:2:13 range=[re.swift:2:13 - line:2:19] typerepr='[UInt8]')) )) (argument_list (argument (member_ref_expr type='String.UTF8View' location=re.swift:2:29 range=[re.swift:2:21 - line:2:29] decl=Swift.(file).String extension.utf8 (declref_expr type='String' location=re.swift:2:21 range=[re.swift:2:21 - line:2:21] decl=re.(file).check(_:_:).encoded@re.swift:1:14 function_ref=unapplied))) ))) (var_decl range=[re.swift:2:9 - line:2:9] "b" type='[UInt8]' interface type='[UInt8]' access=private readImpl=stored writeImpl=stored readWriteImpl=stored)
最新发布
06-10

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值