2

Default

enter image description here

Desired

enter image description here

Changing tintColor on a UITextField changes the selection color, but I can't find any documentation for changing it in a UITextView.

Sashi
  • 2,659
  • 5
  • 26
  • 38
user3454536
  • 33
  • 1
  • 4

2 Answers2

9

Yes, you can change text selection color using tintColor property of UITextView. Use this code to get the expected output.

self.textView.tintColor = .red

Also, You can do this from the storyboard, see the following image.

enter image description here enter image description here

AtulParmar
  • 4,358
  • 1
  • 24
  • 45
0

https://stackoverflow.com/a/26456563/8272698'

I found this answer above, unfortunately it is in objective c

But you can still see how they managed to do it.

- (void)highlight {

    NSRange selectedTextRange = self.textView.selectedRange;

    [attributedString addAttribute:NSBackgroundColorAttributeName
                             value:[UIColor redColor]
                             range:selectedTextRange];

    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (sysVer < 8.0) {
        // iOS 7 fix
        self.textView.scrollEnabled = NO;
        self.textView.attributedText = attributedString;
        self.textView.scrollEnabled = YES;
    } else {
        self.textView.attributedText = attributedString;
    }
}

Basically they created a function called highlight. In the function they are looking for when a user actually highlights a selected portion. self.textView.selectedRange When they get the text range the user has selected. They give it an attribute and provide it colour.

Swift

let selectedText = textView.selectedRange

Create the attribute:

let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]

Provide it your attribute,

textView.textStorage.addAttributes(myAttribute, range: selectedText)

Use this in an action called by sender.

Hope this helps!

Julian Silvestri
  • 1,970
  • 1
  • 15
  • 33