iOS - About Button Click Effect on Cell

Keywords: iOS

https://juejin.im/entry/580f4f33570c350068fea175

In iOS development, there has always been a problem of adding a button to the cell. When we click on the button, it has no highlighting effect. Unless we press the button for a long time, I'll sort out the way to solve this problem.
Links to the original text: http://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7
Solution 1:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Button Click Effect Test";

    self.tableView.delaysContentTouches = NO;

    // iOS7
    for (id view in self.tableView.subviews)
    {
        if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
        {
            if([view isKindOfClass:[UIScrollView class]])
            {
                UIScrollView *scroll = (UIScrollView *) view;
                scroll.delaysContentTouches = NO;
            }
            break;
        }
    }

    // IOS 8 note that I test system iOS 10, do not go this way, go up that way.
    for (id view in self.tableView.subviews)
    {
        if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewCellScrollView"])
        {
            if([view isKindOfClass:[UIScrollView class]])
            {
                UIScrollView *scroll = (UIScrollView *) view;
                scroll.delaysContentTouches = NO;
            }
            break;
        }
    }

    // This approach is equivalent to the combination of the above two loops, and the implementation is more elegant. It is recommended to use it instead of using the above two loops.
    for (id obj in self.tableView.subviews) {
        if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
            [obj setDelaysContentTouches:NO];
        }
    }
}

Solution 2:

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = YES;}];
}

-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesCancelled:touches withEvent:event];
    [self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}

- (void)setDefault
{
    [NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = NO; }];
}

This scheme is simple and rough. We create a UIButton classification and import it into pch file, which completely solves the click effect problem of button. It is simpler than the first scheme.

Posted by smsharif on Fri, 15 Feb 2019 00:30:19 -0800