Skip to main content

Detect url from string and want it highlight?

Take IBOutlet for TextField ,  Button and Lable:

TextField:  To take input from user
Label: To show output to user
Button : To Convert from string to Attributed string with highlighting HTTP string as a URL.

Code:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UILabel *label;

-(IBAction)click:(id)sender;

@end
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
  
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)click:(id)sender
{
  
    NSMutableArray *mutableWords = [[_textField.text componentsSeparatedByString: @" "] mutableCopy];
    NSLog(@"MutableWords: %@",mutableWords);
    NSMutableAttributedString *resultString;
    NSMutableAttributedString *attStr1,*attStr2;
    resultString = [[NSMutableAttributedString alloc]init];
  


    for (NSString *string in mutableWords)
    {
      
        NSRange match;
      
        attStr1 = [[NSMutableAttributedString alloc] initWithString:string];
        match = [string rangeOfString: @"http"];
        if (match.location == NSNotFound)
        {
            [resultString appendAttributedString:attStr1];
          
            NSLog(@"string:%@",resultString);
        }
        else
        {
            attStr2 = [[NSMutableAttributedString alloc] initWithString:string];

             [attStr2 addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleThick) range:NSMakeRange(0, [attStr2 length])];
            [attStr2 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, [attStr2 length])];

            [resultString appendAttributedString:attStr2];
          
        }

    }
  
    _label.attributedText = (NSAttributedString*)resultString;
   
}

@end

Input:

OutPut:



or

Do it in a smart way:

1. TextField: For input text (inputTextField)
2. TextView: For Output (outPutTextView)
3. Button: On click action

Button Onclick Action:

   self.textView.text = self.inputTextField.text;
   self. outPutTextView.editable = NO;

   self. outPutTextView.dataDetectorTypes = UIDataDetectorTypeAll;



Comments

Like us on Facebbok