在Swift/Obj-C中,可以通过以下步骤来实现通过单击add按钮来添加一个单元格,并在表视图中创建一个单元格:
numberOfRowsInSection
中,返回表视图的行数。cellForRowAtIndexPath
中,创建并返回一个自定义的表视图单元格。reloadData
方法,刷新表视图。下面是一个示例代码:
Swift:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var textField: UITextField!
var data = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
// 表视图的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
// 创建并返回表视图单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
// 添加按钮的点击事件
@IBAction func addButtonClicked(_ sender: UIButton) {
if let text = textField.text, !text.isEmpty {
data.append(text)
tableView.reloadData()
textField.text = ""
}
}
}
Obj-C:
#import "ViewController.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) NSMutableArray *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.data = [[NSMutableArray alloc] init];
}
// 表视图的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.data.count;
}
// 创建并返回表视图单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.data[indexPath.row];
return cell;
}
// 添加按钮的点击事件
- (IBAction)addButtonClicked:(UIButton *)sender {
NSString *text = self.textField.text;
if (text.length > 0) {
[self.data addObject:text];
[self.tableView reloadData];
self.textField.text = @"";
}
}
@end
在上述示例代码中,我们创建了一个表视图,并在视图控制器中添加了一个TextField和一个按钮。当点击按钮时,我们获取TextField的值,并将其添加到数据源数组中。然后,调用表视图的reloadData
方法来刷新表视图,从而在表视图中创建一个新的单元格,显示添加的值。
注意:示例代码中的表视图单元格标识符为"Cell",需要在故事板或代码中设置相应的标识符。
领取专属 10元无门槛券
手把手带您无忧上云