Как реализовать прокрутку вправо в ячейку UITableView, подобную iOS Mail
Я пытаюсь воспроизвести тот же метод, который Apple использует в своем почтовом приложении для маркировки почты как непрочитанной или "Отметить как непрочитанную", когда вы прокладываете слева направо внутри почтового ящика.
![Screenshot of Mail inside iOS 8.1 Mail app]()
Я нашел аналогичные решения, но только для жестов swiping справа налево. Я надеялся, что это же решение было доступно как часть Apple SDK в противоположном направлении.
Как я могу получить один и тот же эффект жевательности слева направо, как это делает приложение iOS Mail?
Ответы
Ответ 1
Я нашел похожие решения, но только для жестов справа налево.
SWTableViewCell имеет все необходимые параметры.
При деинкретировании ячейки только нужно установить левый/правый набор кнопок по мере необходимости.
cell.leftUtilityButtons = [self leftButtons];
cell.rightUtilityButtons = [self rightButtons];
cell.delegate = self;
И, установив контроллер представления в качестве его делегата, вы можете прослушивать нажатие кнопки.
Полная информация о том, как реализовать, находится в этой ссылке
Пример 1:
![enter image description here]()
Пример 2:
![enter image description here]()
Если вы ищите кнопки, расположенные вертикально, просмотрите этот.
Ответ 2
Я обычно реализую его на уровне таблицы.
- (void)viewDidLoad
{
[super viewDidLoad];
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(leftSwipe:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.tableView addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(rightSwipe:)];
recognizer.delegate = self;
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.tableView addGestureRecognizer:recognizer];
}
Затем вы контролируете направление и можете настроить по желанию.
- (void)leftSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
//do you left swipe stuff here.
}
- (void)rightSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
//do you right swipe stuff here. Something usually using theindexPath that you get that way
CGPoint location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
}
Кредит переходит в Jade Mind
Ответ 3
Принятый ответ в указанной вами ссылке предназначен для обоих направлений прокрутки.
Обратите внимание, что gestureRecognizer.direction
возвращает YES
как для UISwipeGestureRecognizerDirectionLeft
, так и UISwipeGestureRecognizerDirectionRight
.
Вам просто нужно изменить пару вещей:
Измените селектор, который вызывается при прокрутке, поэтому он вызовет ваш метод, а не тот, который указан в примере сообщения,
И измените направление салфетки, чтобы оно было слева направо, а не для обоих направлений, как это сейчас, так как, как я понимаю, вы пытаетесь установить одностороннюю салфетки.
Итак, ваш код должен выглядеть так:
// In cellForRowAtIndexPath:, where you create your custom cell
cell.tableView=tableView;
cell.indexPath=indexPath;
UISwipeGestureRecognizer *swipeGestureRecognizer=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(YOUR_METHOD_GOES_HERE)];
[cell addGestureRecognizer:swipeGestureRecognizer];
.
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if([[gestureRecognizer view] isKindOfClass:[UITableViewCell class]] && ((UISwipeGestureRecognizer*)gestureRecognizer.direction==UISwipeGestureRecognizerDirectionRight)
return YES;
}
Обратите внимание, что вы также можете использовать ответ ниже принятого ответа и просто изменить свойство распознавания жестов direction
как UISwipeGestureRecognizerDirectionRight
вместо текущего направления в примере, которое UISwipeGestureRecognizerDirectionLeft
.
Если вы решите реализовать это, ваш viewController должен реализовать делегата распознавателя жестов, и ваш код должен выглядеть так:
// Call this method in viewDidLoad
- (void)setUpLeftSwipe {
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(swipeRightt:)];
[recognizer setDirection:UISwipeGestureRecognizerDirectionRight];
[self.tableView addGestureRecognizer:recognizer];
recognizer.delegate = self;
}
- (void)swipeRight:(UISwipeGestureRecognizer *)gestureRecognizer {
CGPoint location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
... do something with cell now that i have the indexpath, maybe save the world? ...
}
Примечание. Если я не ошибаюсь, вам нужно создать анимацию для выбора ячейки, так как, я полагаю, анимация ячейки по умолчанию Xcode - только при прокрутке влево.
Кредит переходит к MadhavanRP
и Julian
из предоставленной вами ссылки. Я просто изменил их ответы на набор лучше, чем ваши потребности.
Я не пробовал и реализовал это сам, хотя.
Ответ 4
Используйте свой собственный TableViewCell с прокруткой, как показано ниже:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 120;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
return header_view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array_field1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Schedule_cell";
Custom_Schedule_Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = (Custom_Schedule_Cell *)[Custom_Schedule_Cell cellFromNibNamed:@"Custom_Schedule_Cell"];
}
x = 0;
UILabel *lbl_title =[[UILabel alloc] initWithFrame:CGRectMake(x,0,cell.scroll_view.frame.size.width,cell.scroll_view.frame.size.height)];
[email protected]"Title Array";
[lbl_title setTextAlignment:NSTextAlignmentCenter];
[lbl_title setFont:[UIFont fontWithName:@"Raleway" size:18.0f]];
x += lbl_title.frame.size.width+10;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,0,110,cell.scroll_view.frame.size.height)];
[button setTitle:@"Button1" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor grayColor]];
[button addTarget:self action:@selector(button1:) forControlEvents:UIControlEventTouchDown];
button.tag = indexPath.row;
[button.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button.titleLabel setFont:[UIFont fontWithName:@"Raleway" size:14.0f]];
x += button.frame.size.width+5;
UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(x,0,110,cell.scroll_view.frame.size.height)];
[button2 setTitle:@"Button2" forState:UIControlStateNormal];
[button2 setBackgroundColor:[UIColor grayColor]];
[button2 addTarget:self action:@selector(button2:) forControlEvents:UIControlEventTouchDown];
button2.tag = indexPath.row;
[button2.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button2.titleLabel setFont:[UIFont fontWithName:@"Raleway" size:14.0f]];
x += button2.frame.size.width+5;
UIButton *button3 = [[UIButton alloc] initWithFrame:CGRectMake(x,0,110,cell.scroll_view.frame.size.height)];
[button3 setTitle:@"Button3" forState:UIControlStateNormal];
[button3 setBackgroundColor:[UIColor grayColor]];
[button3 addTarget:self action:@selector(button3:) forControlEvents:UIControlEventTouchDown];
button3.tag = indexPath.row;
[button3.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button3.titleLabel setFont:[UIFont fontWithName:@"Raleway" size:14.0f]];
[cell.scroll_view addSubview:lbl_title];
[cell.scroll_view addSubview:button];
[cell.scroll_view addSubview:button2];
[cell.scroll_view addSubview:button3];
x += button3.frame.size.width+5;
cell.scroll_view.contentSize = CGSizeMake(x,cell.scroll_view.frame.size.height);
cell.scroll_view.showsHorizontalScrollIndicator = NO;
cell.scroll_view.showsVerticalScrollIndicator = NO;
[cell.scroll_view setContentOffset:CGPointMake(0,0) animated:NO];
[cell.scroll_view setPagingEnabled:true];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Custom_Schedule_Cell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
// [selectedCell.scroll_view setContentOffset:CGPointMake(x2,0) animated:NO];
}
-(void)button1:(UIButton *)button
{
NSLog(@"button1 Click ");
[button setBackgroundColor:[UIColor redColor]];
}
-(void)button2:(UIButton *)button
{
NSLog(@"button2 Click");
[button setBackgroundColor:[UIColor greenColor]];
}
-(void)button3:(UIButton *)button
{
NSLog(@"button Click");
[button setBackgroundColor:[UIColor redColor]];
}