我是目标C的新手,我对学习新技术非常感兴趣。
我在标签上有一个uitapgesturer识别器。我正在使用2个标签,当我点击label1加载一些数据表视图时,当我点击标签2时,我想更改tableview。
我没有找到任何解决方案来满足我的要求。所以任何人都帮助我。
建议我在uilabel上点击时如何更改tableview数据。
您可以像以下方式一样执行此操作:
方法1:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
..
..
..
// Here is your stuff for cell
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
[lbl1 setText:@"Label"];
[lbl1 setUserInteractionEnabled:YES];
[cell.contentView addSubview:lbl1];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.tag = [NSIndexPath row];
[tap setNumberOfTapsRequired:1];
[lbl addGestureRecognizer:tap];
...
}
- (void)tapAction:(id)sender {
switch(((UITapGestureRecognizer *)sender).view.tag) {
case 0:
// code for first TableView
break;
case 1:
// code for second TableView
break;
....
}
}
方法2:
在cellForRowAtIndexPath:
方法中:
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.tag = [NSIndexPath row];
...
处理程序方法:
- (void)tapAction:(id)sender
{
switch(((UITapGestureRecognizer *)sender).tag)
{
case 0:
NSLog(@"Tap action 1");
break;
case 1:
NSLog(@"tap action 2");
break;
..... }
我假设您已经设置了tableView的数据源/委托方法?然后在标签被轻拍并简单地调用
时更改这些方法中的必要内容。 [self.tableView reloadData]
如果您对我的意思一无所知,那么我建议您先阅读一些有关tableviews的手册,然后再开始询问问题:)
欢迎来到堆栈溢出!
此答案应该有助于为您清除事物,并使您对如何使用表视图和按钮做您需要的事情有更深入的了解。
第一个
在Alladinian的评论中,我强烈建议切换到UIButton
对象,而不是使用UILabel
对象。这样,您的元素仍然可以显示您的文本(就像标签一样)> 您可以使用按钮类的内置目标功能。
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
第二
关于您的问题,同样,只需使用针对这种情况而设计的已内置方法:
- (void)reloadData;
可以使用/设置UITableViewDelegate
和UITableViewDataSource
获得此方法。这样:这是一个通用UIViewController
类的示例,该类别符合(可以正确使用)方便的UITableView
委托。
标题文件(SomeClassController.h)
// SomeClassController.h
#import <UIKit/UIKit.h>
@interface SomeClassController : UIViewController <UITableViewDelegate, UITableViewDataSource>
// do anything here. properties, methods, etc :)
@property (nonatomic, ...) UITableView *tableView;
@end
实现文件(someclasscontroller.m)
// ...
- (void)viewDidLoad {
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
现在,通过使用UIButton
对象,您可以设置一种方法,该方法将通过执行方法来处理触摸屏幕的用户。喜欢这里:
- (void)viewDidLoad {
...
[someButton addTarget:self action:@selector(didTouchButton:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)didTouchButton:(__kindof UIButton *)button {
// Here you received the users touch event on the button, do what you like!
// As your question asked how to reload table data, simply add this line
// after following my other steps.
[self.tableView reloadData]; // Here the magic is done!
// This method will automatically reload the table view to display the
// most recently updated data you have given it.
}
确保在重新加载之前更改数据,否则可能不会在视觉上更改或 content Wise。
快乐编码!