Search code examples
objective-cxcodeuilabeluiswipegesturerecognizerswipe-gesture

swipe gesture strike through text


I have been trying to come out a solution for using swipe gesture to the right and makes the text on a label.text with strike through effect, swipe again to remove the strike through and leaves the original text intact. Any example of codes as to how to do this? This is a XCode question.

if ([***this is the part i need help with***])
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[self.EditItem valueForKey:@"eventName"]];
    [attributeString addAttribute:NSStrikethroughStyleAttributeName
                            value:@1
                            range:NSMakeRange(0, [attributeString length])];
    self.nameTextField.attributedText = attributeString;
    [self.EditItem setValue:[NSString stringWithFormat:@"Completed"] forKey:@"eventName"];
    NSLog(@"Swiped to the right");
}
else
{
    [NSString initWithString:[self.EditItem valueForKey:@"eventName"]];
    NSLog(@"normal text no strike through");
}

Solution

  • You could try a simple gesture recogniser like this..

    Add the following in your viewDidLoad or similar

    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(strikeThrough)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.nameTextField addGestureRecognizer:swipe];
    

    Then setup the strikeThrough method to change the text to strikethrough - if you only have one textfield just add a toggle so that you can turn the strikethrough on and off.

    bool stricken;
    
    - (void) strikeThrough {
    
        if (stricken) {
    
            self.nameTextField.text = self.nameTextField.text;
    
            stricken = false;
    
        } else {
    
            NSDictionary* attributes = @{ NSStrikethroughStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
            NSAttributedString* attrText = [[NSAttributedString alloc] initWithString:self.nameTextField.text attributes:attributes];
            self.nameTextField.attributedText = attrText;
    
            stricken = true;
    
      }
    
    }