Swift 实践之简单购物(UITableView的使用)

这篇博客介绍了一个使用Swift和Storyboard构建的简单购物应用。通过练习,作者展示了如何利用UITableView添加产品到购物清单,并实现点击选择及状态显示功能。教程包括创建新工程、在Storyboard中添加控件、编写相关代码以及展示最终效果。

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

Shopping应用程序

创建一个名为Shopping的工程
描述:通过该练习主要学习UITableView,Storyboard的使用和一些简单的代理传值的学习. 主要实现的是点击保存商品后,会在购物清单中添加刚刚我们新增的产品,选中某行购物清单之后,点击已经购买之后,购物清单相应的商品会变为绿色,已记录我们刚刚的操作.
使用Stroryboard添加相应控件

项目目录为:

这里写图片描述

Storyboard结构图如下:

这里写图片描述

代码实现

  • ViewController的代码实现
//
//  ViewController.swift
//  Swift_Shopping
//
//  Created by 周文春 on 16/3/7.
//  Copyright © 2016年 周文春. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,NewItemViewControllerDelegate  {

    @IBOutlet weak var tableView: UITableView!

    //数据源
    var toBuyItems = [ Item(itemName: "牛奶", brandName: "三元"),
                       Item(itemName: "红烧牛肉面", brandName: "康师傅"),
                       Item(itemName: "桃汁", brandName: "汇源"),
                       Item(itemName: "巧克力", brandName: "德芙"),
                       Item(itemName: "地板净", brandName: "滴露"),
                       Item(itemName: "洗发水", brandName: "飘柔")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }

    //UITableView的两个必须实现的数据源方法
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toBuyItems.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        let item = toBuyItems[indexPath.row]
        if item.isBuy {
            cell.textLabel?.textColor = UIColor.greenColor()
        }else{
            cell.textLabel?.textColor = UIColor.redColor()
        }
        cell.textLabel?.text = item.itemName
        cell.detailTextLabel?.text = item.brandName
        return cell
    }
    //UITableView的代理方法
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        performSegueWithIdentifier("itemSegue", sender: indexPath.row)
    }

    //通过itemSegue和newItemSegue来标识进入下一个页面
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if  segue.identifier == "itemSegue" {
            let destination: ItemViewController = segue.destinationViewController as! ItemViewController
            if sender is Int {
                let item = toBuyItems[sender as! Int]
                destination.item = item
            }
        }else if segue.identifier == "newItemSegue" {
            let destination: NewItemViewController = segue.destinationViewController as! NewItemViewController
            destination.delegate = self
        }

    }

    //实现NewItemViewController里面的协议方法
    func addNewItem(controller: NewItemViewController, item: Item) {
        //将NewItemViewController里面的实例对象Item加入到数据源toBuyItems中
        toBuyItems.append(item)
        //刷新数据
        tableView.reloadData()
        //销毁NewItemViewController对象
        controller.dismissViewControllerAnimated(true, completion: nil)
    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
  • NewItemViewController的代码实现
//
//  NewItemViewController.swift
//  Swift_Shopping
//
//  Created by 周文春 on 16/3/7.
//  Copyright © 2016年 周文春. All rights reserved.
//

import Foundation
import UIKit

//设置代理方法
protocol NewItemViewControllerDelegate {
    func addNewItem(controller: NewItemViewController, item: Item)
}
class NewItemViewController: UIViewController {

    @IBOutlet weak var brandNameTF: UITextField!
    @IBOutlet weak var itemNameTF: UITextField!
    //声明一个Item的实例对象
    var item: Item?
    //声明一个代理
    var delegate: NewItemViewControllerDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func saveItem(sender: UIButton) {
        if itemNameTF.text != nil && brandNameTF.text != nil {
            item = Item(itemName: itemNameTF.text!, brandName: brandNameTF.text!)
        }
        if ((delegate) != nil) {
            delegate?.addNewItem(self, item: item!)
        }

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning() 
    }
}
  • ItemViewController的代码实现


//
//  ItemViewController.swift
//  Swift_Shopping
//
//  Created by 周文春 on 16/3/7.
//  Copyright © 2016年 周文春. All rights reserved.
//

import Foundation
import UIKit

class ItemViewController: UIViewController {

    @IBOutlet weak var brandNameLable: UILabel!
    @IBOutlet weak var itemNameLable: UILabel!

    var item: Item?
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(animated: Bool) {

        if item != nil {
            itemNameLable.text = item?.itemName
            brandNameLable.text = item?.brandName
        }
    }
    @IBAction func isBuy(sender: UIButton) {
        if item?.isBuy == false {
            item?.isBuy = true
            itemNameLable.textColor = UIColor.greenColor()
        }else{
            item?.isBuy = false
            itemNameLable.textColor = UIColor.redColor()
        }
        print(item?.description())

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning() 
    }
}
  • Item文件的代码实现

//
//  Item.swift
//  Swift_Shopping
//
//  Created by 周文春 on 16/3/8.
//  Copyright © 2016年 周文春. All rights reserved.
//

import Foundation

class Item {
    var itemName: String = ""
    var brandName: String = ""
    var isBuy: Bool = false

    //指定构造器
    init (itemName: String, brandName: String, isBuy: Bool) {
        self.itemName = itemName
        self.brandName = brandName
        self.isBuy = isBuy
    }

    //便利构造器
    convenience init (itemName: String) {
        self.init (itemName: itemName, brandName: "", isBuy: false)
    }

    //便利构造器
    convenience init (itemName: String, brandName: String) {
        self.init (itemName: itemName, brandName: brandName, isBuy: false)
    }

    //Item的描述方法,用于在调试时返回类信息
    func description() -> String {
        return ("itemName: \(itemName)  brandName: \(brandName)  isBuy: \(isBuy)")
    }


}

效果图如下

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值