Как передать контакт с UITextView на UITableViewCell

У меня есть UITextView в пользовательском UITableViewCell. Textview работает правильно (прокручивает, показывает текст и т.д.), Но мне нужно, чтобы пользователи могли использовать ячейку таблицы и перейти на другой экран. Прямо сейчас, если вы нажмете края ячейки таблицы (то есть за пределами UItextView), следующее представление будет правильно вызвано. Но, очевидно, внутри uitextview штрихи захватываются и не пересылаются в ячейку таблицы.

Я нашел сообщение, в котором говорилось о подклассе UITextView для пересылки касаний. Я пробовал это без везения. Реализация ниже. Мне интересно, может быть, а) супер моего текстового обзора не является uitableviewcell, и поэтому мне нужно передать прикосновение каким-то другим способом или б) Если супер - это uitableviewcell, если мне нужно передать что-то еще? Любая помощь будет высоко оценена.

#import "ScrollableTextView.h"

@implementation ScrollableTextView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (parentScrollView) {
        [parentScrollView touchesBegan:touches withEvent:event];
    }
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    if (parentScrollView) {
        [parentScrollView touchesCancelled:touches withEvent:event];
    }
    [super touchesCancelled:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (parentScrollView) {
        [parentScrollView touchesEnded:touches withEvent:event];
    }
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (parentScrollView) {
        [parentScrollView touchesMoved:touches withEvent:event];
    }
    [super touchesMoved:touches withEvent:event];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

@end

Ответы

Ответ 1

Попробуйте [theTextView setUserInteractionEnabled:NO]; Если пользователь должен иметь возможность редактировать содержимое TextView, у вас может возникнуть проблема с дизайном.

Swift 3: theTextView.isUserInteractionEnabled = false

Раскадровка: отметьте флажок "Взаимодействие с пользователем".

Ответ 2

Я знаю, что этот вопрос задан 5 лет назад, но по-прежнему очень необходимо, чтобы какое-то приложение имело интерактивную ячейку с идентификаторами UIDataDetectors.

Итак, вот подкласс UITextView, который я составил, чтобы соответствовать этому конкретному поведению в UITableView

-(id) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
    }
    return self;
}

- (BOOL)canBecomeFirstResponder {
    return NO;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UIView *obj = self;

    do {
        obj = obj.superview;
    } while (![obj isKindOfClass:[UITableViewCell class]]);
    UITableViewCell *cell = (UITableViewCell*)obj;

    do {
        obj = obj.superview;
    } while (![obj isKindOfClass:[UITableView class]]);
    UITableView *tableView = (UITableView*)obj;

    NSIndexPath *indePath = [tableView indexPathForCell:cell];
    [[tableView delegate] tableView:tableView didSelectRowAtIndexPath:indePath];
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    return YES;
}

Вы можете изменить это в соответствии с вашими потребностями...

Надеюсь, что это поможет кому-то.

Ответ 3

Проблема с вашим решением заключается в том, что если вы поместите UITextView внутри UITableViewCell, его супервизор не будет фактической ячейкой. Там даже небольшое различие между iOS 7 и iOS 8 в структуре ячеек. Что вам нужно сделать, это сверлить (или просверлить) по иерархии, чтобы получить экземпляр UITableViewCell.

Я использую и изменяю цикл @TheSquad while для получения UITableViewCell и присваиваю его свойству. Затем переопределите эти сенсорные методы, используйте метод соты, когда это необходимо, и просто используйте методы супер-сенсорного метода, чтобы получить поведение по умолчанию.

// set the cell as property
@property (nonatomic, assign) UITableViewCell *superCell;

- (UITableViewCell *)superCell {
    if (!_superCell) {
        UIView *object = self;

        do {
            object = object.superview;
        } while (![object isKindOfClass:[UITableViewCell class]] && (object != nil));

        if (object) {
            _superCell = (UITableViewCell *)object;
        }
    }

    return _superCell;
}

#pragma mark - Touch overrides

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.superCell) {
        [self.superCell touchesBegan:touches withEvent:event];
    } else {
        [super touchesBegan:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.superCell) {
        [self.superCell touchesMoved:touches withEvent:event];
    } else {
        [super touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.superCell) {
        [self.superCell touchesEnded:touches withEvent:event];
    } else {
        [super touchesEnded:touches withEvent:event];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.superCell) {
        [self.superCell touchesEnded:touches withEvent:event];
    } else {
        [super touchesCancelled:touches withEvent:event];
    }

}