Swift - 給表格添加編輯功能(刪除,插入)

1,下面的樣例是給表格UITableView添加編輯功能:swift

(1)給表格添加長按功能,長按後表格進入編輯狀態
(2)在編輯狀態下,第一個分組處於刪除狀態,第二個分組處於插入狀態
(3)點擊刪除圖標,刪除對應條目
(4)點擊添加圖標,插入一條新數據

2,效果圖
       

       

3,代碼以下

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import UIKit
 
class ViewController : UIViewController , UITableViewDelegate ,
UITableViewDataSource , UIGestureRecognizerDelegate {
     
     var tableView: UITableView ?
     
     var allnames: Dictionary < Int , [ String ]>?
     
     var adHeaders:[ String ]?
     
     override func loadView() {
         super .loadView()
     }
     
     override func viewDidLoad() {
         super .viewDidLoad()
         
         //初始化數據,這一次數據,咱們放在屬性列表文件裏
         self .allnames =  [
             0:[ String ]([
                 "UILabel 標籤" ,
                 "UIButton 按鈕" ]),
             1:[ String ]([
                 "UIDatePiker 日期選擇器" ,
                 "UITableView 表格視圖" ])
         ];
         
         println ( self .allnames)
         
         self .adHeaders = [
             "常見 UIKit 控件" ,
             "高級 UIKit 控件"
         ]
         
         //建立表視圖
         self .tableView = UITableView (frame: self .view.frame, style: UITableViewStyle . Grouped )
         self .tableView!.delegate = self
         self .tableView!.dataSource = self
         //建立一個重用的單元格
         self .tableView!.registerClass( UITableViewCell . self , forCellReuseIdentifier: "SwiftCell" )
         self .view.addSubview( self .tableView!)
         
         //建立表頭標籤
         var headerLabel = UILabel (frame: CGRectMake (0, 0, self .view.bounds.size.width, 30))
         headerLabel.backgroundColor = UIColor .blackColor()
         headerLabel.textColor = UIColor .whiteColor()
         headerLabel.numberOfLines = 0
         headerLabel.lineBreakMode = NSLineBreakMode . ByWordWrapping
         headerLabel.text = "UIKit 控件"
         headerLabel.font = UIFont .italicSystemFontOfSize(20)
         self .tableView!.tableHeaderView = headerLabel
         
         //綁定對長按的響應
         var longPress =  UILongPressGestureRecognizer (target: self ,
             action: Selector ( "tableviewCellLongPressed:" ))
         //代理
         longPress.delegate = self
         longPress.minimumPressDuration = 1.0
         //將長按手勢添加到須要實現長按操做的視圖裏
         self .tableView!.addGestureRecognizer(longPress)
     }
      
     func tableviewCellLongPressed(gestureRecognizer: UILongPressGestureRecognizer )
     {
         if (gestureRecognizer.state == UIGestureRecognizerState . Began )
         {
             println ( "UIGestureRecognizerStateBegan" );
         }
         if (gestureRecognizer.state == UIGestureRecognizerState . Changed )
         {
             println ( "UIGestureRecognizerStateChanged" );
         }
         
         if (gestureRecognizer.state == UIGestureRecognizerState . Ended )
         {
             println ( "UIGestureRecognizerStateEnded" );
             //在正常狀態和編輯狀態之間切換
             if ( self .tableView!.editing == false )
             {
                 self .tableView!.setEditing( true , animated: true )
             }
             else
             {
                 self .tableView!.setEditing( false , animated: true )
                 
             }
         }
     }
     
     //在本例中,有2個分區
     func numberOfSectionsInTableView(tableView: UITableView !) -> Int {
         return 2
     }
     
     //返回表格行數(也就是返回控件數)
     func tableView(tableView: UITableView , numberOfRowsInSection section: Int ) -> Int {
         var data = self .allnames?[section]
         return data!.count
     }
     
     // UITableViewDataSource協議中的方法,該方法的返回值決定指定分區的頭部
     func tableView(tableView: UITableView , titleForHeaderInSection
         section: Int )-> String
     {
         var headers =  self .adHeaders!;
         return headers[section];
     }
     
     // UITableViewDataSource協議中的方法,該方法的返回值決定指定分區的尾部
     func tableView(tableView: UITableView , titleForFooterInSection
         section: Int )-> String
     {
         var data = self .allnames?[section]
         return "有\(data!.count)個控件"
     }
     
     //建立各單元顯示內容(建立參數indexPath指定的單元)
     func tableView(tableView: UITableView , cellForRowAtIndexPath indexPath: NSIndexPath )
         -> UITableViewCell
     {
         //爲了提供表格顯示性能,已建立完成的單元需重複使用
         let identify: String = "SwiftCell"
         //同一形式的單元格重複使用,在聲明時已註冊
         let cell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath)
             as UITableViewCell
         cell.accessoryType = UITableViewCellAccessoryType . DisclosureIndicator
         
         var secno = indexPath.section
         var data = self .allnames?[secno]
         cell.textLabel?.text = data![indexPath.row]
         
         return cell
     }
     
     // UITableViewDelegate 方法,處理列表項的選中事件
     func tableView(tableView: UITableView !, didSelectRowAtIndexPath indexPath: NSIndexPath !)
     {
         self .tableView!.deselectRowAtIndexPath(indexPath, animated: true )
         
         var itemString = self .allnames![indexPath.section]![indexPath.row]
         
         var alertview = UIAlertView ();
         alertview.title = "提示!"
         alertview.message = "你選中了【\(itemString)】" ;
         alertview.addButtonWithTitle( "肯定" )
         alertview.show();
     }
     
     func tableView(tableView: UITableView !, editingStyleForRowAtIndexPath indexPath: NSIndexPath !)
         -> UITableViewCellEditingStyle
     {
         if (indexPath.section == 1)
         {
             return UITableViewCellEditingStyle . Insert
         }
         return UITableViewCellEditingStyle . Delete
     }
     
     func tableView(tableView: UITableView !,
         titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath !) -> String !
     {
         var data = self .allnames?[indexPath.section]!
         
         var itemString = data![indexPath.row] as String
         return "肯定刪除\(itemString)?"
     }
     
     func tableView(tableView: UITableView !, commitEditingStyle editingStyle: UITableViewCellEditingStyle ,
         forRowAtIndexPath indexPath: NSIndexPath !)
     {
         if (editingStyle == UITableViewCellEditingStyle . Delete )
         {
             self .allnames?[indexPath.section]?.removeAtIndex(indexPath.row)
             
             self .tableView!.reloadData()
             self .tableView!.setEditing( true , animated: true )
             println ( "你確認了刪除按鈕" )
            // Array
         }
         else if (editingStyle == UITableViewCellEditingStyle . Insert )
         {
             self .allnames?[indexPath.section]?.insert( "插入一項新的" , atIndex: indexPath.row+1)
             println ( "你按下了插入按鈕" )
             self .tableView!.reloadData()
         }
     }
     
     override func didReceiveMemoryWarning() {
         super .didReceiveMemoryWarning()       
         // Dispose of any resources that can be recreated.
     }
}
相關文章
相關標籤/搜索