Select and highlight text on a label

I want to select and then highlight the same text on a label with a specific color. This can be achieved with gestures. And I have to keep the position of the selected part, even if the application ends, so when the user returns, they can see that the selected part

thank

+5
source share
2 answers

Yes, you can use a gesture with yours UILabelto highlight text by changing the background color or your text UILabel.

UILabel NSUserDefaults , .

isLabelHighlighted BOOL UILabel.

UITapGestureRecognizer* myLabelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(LabelClicked:)];
[myLabelView setUserInteractionEnabled:YES];
[myLabelView addGestureRecognizer:myLabelGesture];


-(void)LabelClicked:(UIGestureRecognizer*) gestureRecognizer
{
    if(isLabelHighlighted)
    { 
         myLabelView.highlightedTextColor = [UIColor greenColor];
    }
    else 
    {
         myLabelView.highlightedTextColor = [UIColor redColor];
    }
}

UILabel.

[[NSUserDefaults standardUserDefaults] setBool:isLabelHighlighted forKey:@"yourKey"];

, .

isLabelHighlighted = [[NSUserDefaults standardUserDefaults] boolForKey:@"yourKey"];
+6

NSUserDefaults , UITapGestureRecognizer , UIGestureRecognizerStateEnded

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizerAction:)];
    longPressGestureRecognizer.minimumPressDuration = 0.01;
    [label setUserInteractionEnabled:YES];
    [label addGestureRecognizer:longPressGestureRecognizer];
}


- (void)longPressGestureRecognizerAction:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateEnded)
    {
        label.alpha = 0.3;
    }
    else
    {
        label.alpha = 1.0;

        CGPoint point = [gestureRecognizer locationInView:label];
        BOOL containsPoint = CGRectContainsPoint(label.bounds, point);

        if (containsPoint)
        {
            // Action (Touch Up Inside)
        }
    }
}
+1

All Articles