Skip to content

Instantly share code, notes, and snippets.

@iOSDigital
Last active January 2, 2016 22:19
Show Gist options
  • Save iOSDigital/8369082 to your computer and use it in GitHub Desktop.
Save iOSDigital/8369082 to your computer and use it in GitHub Desktop.
iOS: a method to add basic html tags into a UITextView. In this example there are 4 buttons, bold, italic, underline, link. In my app these buttons are in an inputAccessoryView, and they are tagged 1,2,3,4. If no text is selected, the method just inserts the tags at the cursor position, and then sets the cursor position in between the opening an…
-(IBAction)insertHTMLTags:(id)sender {
NSRange selectRange = [textComment selectedRange];
NSUInteger selectLength = selectRange.length;
NSString *openingTag,*closingTag;
switch ([sender tag]) {
case 1:
openingTag = @"<strong>";
closingTag = @"</strong>";
break;
case 2:
openingTag = @"<em>";
closingTag = @"</em>";
break;
case 3:
openingTag = @"<u>";
closingTag = @"</u>";
break;
case 4:
openingTag = @"<a href=\"\">";
closingTag = @"</a>";
break;
default:
break;
}
if (selectLength == 0) {
// No text selected - just add the tags then put cursor between them ready for typing
[textComment insertText:[NSString stringWithFormat:@"%@%@",openingTag,closingTag]];
NSRange newRange = [textComment selectedRange];
NSUInteger newLocation = newRange.location - closingTag.length;
[textComment setSelectedRange:NSMakeRange(newLocation, 0)];
} else {
// Some text selected - wrap the selection with the tags
NSString *selectedText = [textComment.text substringWithRange:selectRange];
NSString *stringToInsert = [NSString stringWithFormat:@"%@%@%@",openingTag,selectedText,closingTag];
[textComment insertText:stringToInsert];
// If it's a link, then put the cursor between the href="" ready to paste link
if ([sender tag] == 4) {
NSUInteger newLocation = closingTag.length + selectLength + 2;
NSUInteger currentLocation = textComment.selectedRange.location;
[textComment setSelectedRange:NSMakeRange(currentLocation - newLocation, 0)];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment