swift UITableView使用

1.新建RootViewController类

//
//  RootViewController.swift
//  UITableViewDemo
//
//  Created by 赵超 on 14-6-21.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

import UIKit

class RootViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var tableView : UITableView?

var items = ["武汉","上海","北京","深圳","广州","重庆","香港","台海","天津"]
    var leftBtn:UIButton?
    var rightButtonItem:UIBarButtonItem?

    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
        setupRightBarButtonItem()
        setupLeftBarButtonItem()
        self.leftBtn!.userInteractionEnabled = true

        // Do any additional setup after loading the view.
    }

    func initView(){
        // 初始化tableView的数据
        self.tableView=UITableView(frame:self.view.frame,style:UITableViewStyle.Plain)
        // 设置tableView的数据源
        self.tableView!.dataSource=self
        // 设置tableView的托付
        self.tableView!.delegate = self
        //
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view.addSubview(self.tableView!)

    }
    //加左边button
    func setupLeftBarButtonItem()
    {
        self.leftBtn = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
        self.leftBtn!.frame = CGRectMake(0,0,50,40)
        self.leftBtn?.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        self.leftBtn?.setTitle("Edit", forState: UIControlState.Normal)
        self.leftBtn!.tag = 100
        self.leftBtn!.userInteractionEnabled = false
        self.leftBtn?.addTarget(self, action: "leftBarButtonItemClicked", forControlEvents: UIControlEvents.TouchUpInside)
        var barButtonItem = UIBarButtonItem(customView: self.leftBtn)
        self.navigationItem!.leftBarButtonItem = barButtonItem
    }
    //左边button事件
    func leftBarButtonItemClicked()
    {
        println("leftBarButton")
        if (self.leftBtn!.tag == 100)
        {
            self.tableView?.setEditing(true, animated: true)
            self.leftBtn!.tag = 200
            self.leftBtn?.setTitle("Done", forState: UIControlState.Normal)
            //将添加button设置不能用
            self.rightButtonItem!.enabled=false
        }
        else
        {
            //恢复添加button
             self.rightButtonItem!.enabled=true
            self.tableView?.setEditing(false, animated: true)
            self.leftBtn!.tag = 100
            self.leftBtn?.setTitle("Edit", forState: UIControlState.Normal)
        }

    }

    //加右边button
    func setupRightBarButtonItem()
    {
         self.rightButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Plain, target: self,action: "rightBarButtonItemClicked")
        self.navigationItem!.rightBarButtonItem = self.rightButtonItem

    }
    //添加事件
    func rightBarButtonItemClicked()
    {

        var row = self.items.count
        var indexPath = NSIndexPath(forRow:row,inSection:0)
        self.items.append("杭州")
        self.tableView?.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)

    }

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

    //总行数
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        return self.items.count
    }

    //载入数据
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{

        let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        var row=indexPath.row as Int
        cell.textLabel.text=self.items[row]
        cell.imageView.image = UIImage(named:"green.png")
        return cell;

    }

    //删除一行
   func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!){
        var index=indexPath.row as Int
        self.items.removeAtIndex(index)
        self.tableView?

.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
        NSLog("删除\(indexPath.row)")
    }
        //选择一行
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
        let alert = UIAlertView()
        alert.title = "提示"
        alert.message = "你选择的是\(self.items[indexPath.row])"
        alert.addButtonWithTitle("Ok")
        alert.show()
    }

}

2.APPDelegate.swift调用

//
//  AppDelegate.swift
//  UITableViewDemo
//
//  Created by 赵超 on 14-6-21.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        var rootView=RootViewController()
        var nav=UINavigationController(rootViewController:rootView)
        self.window!.rootViewController = nav;

        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

3.效果

完整project代码 :https://github.com/whzhaochao/IOS-Swift-UITableViewDemo

时间: 2024-10-17 05:50:44

swift UITableView使用的相关文章

Swift - UITableView展开缩放动画

效果 源码 https://github.com/YouXianMing/Swift-Animations // // HeaderViewTapAnimationController.swift // Swift-Animations // // Created by YouXianMing on 16/8/9. // Copyright © 2016年 YouXianMing. All rights reserved. // import UIKit class HeaderViewTapA

Swift - UITableView状态切换效果

效果 源码 https://github.com/YouXianMing/Swift-Animations // // TableViewTapAnimationController.swift // Swift-Animations // // Created by YouXianMing on 16/8/7. // Copyright © 2016年 YouXianMing. All rights reserved. // import UIKit class TableViewTapAni

IOS SWIFT UITableView 实现简单微博列表

// // Weibo.swift // UITableViewCellExample // // Created by XUYAN on 15/8/15. // Copyright (c) 2015年 com.world. All rights reserved. // import Foundation class Weibo { //属性 var id : UInt32 var img : String! var username : String! var mbtype : String

SWIFT UITableView的基本用法

import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UI

IOS Swift UITableView

选中后消失     func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {         tableView.deselectRowAtIndexPath(indexPath, animated: true)     }

Swift 集成Alamofire/Kingfisher/MJRefresh/MBProgressHUD的小项目

前些时做的Swift版本的瀑布流的Demo<Swift UITableView瀑布流/NSURLConnection异步网络请求>时,使用的是NSURLConnection做的网络异步请求,图片的异步加载使用的是GCD做的.在使用的过程中,网络请求部分是没有什么问题的,但是在图片的异步加载时,由于图片没有缓存,所以在上下滑动的时候,需要不断的加载图片,所以用户体验不好. 在OC中,我们有AFNetworking和SDWebimage做网络的加载和图片的加载.那么在Swift中也是有类似的:Al

Swift的一些问题

一些Swift的问题列表: How to use a Objective-C #define from Swift How do I convert an NSDictionary to a Swift Dictionary<String, NSObject>? Swift: 'var' declaration without getter/setter method not allowed here how to create generic protocols in swift iOS?

iOS播放器、Flutter高仿书旗小说、卡片动画、二维码扫码、菜单弹窗效果等源码

iOS精选源码 全网最详细购物车强势来袭 一款优雅易用的微型菜单弹窗(类似QQ和微信右上角弹窗) swift, UITableView的动态拖动重排CCPCellDragger 高仿书旗小说 Flutter版,支持iOS.Android NKAVPlayer 轻量级视频播放.控制,iOS AVPlayer RN 仿微信朋友圈 SwiftScan 二维码/条形码扫描.生成,仿微信.支付宝 Mac上解压Assets.car文件的小工具cartool tispr-card-stack - swift

swift:创建表格UITableView

用swift创建单元格和用iOS创建单元格形式基本相同,就是语法上有些异样.swift中调用成员方法不再使用[ ]来发送消息,而是使用.成员方法的形式调用成员函数.这种格式非常类似于java中的点成员运算符.swift中对其他类的引用不用导入头文件.这里就不废话了,现在纯代码创建UITableview实例如下: 具体实例如下: 1.首先用swift创建一个工程Project 2.再用swift创建一个Person类,生成Person.swift文件 3.在Perosn.swift文件中将设置的属