我需要在UITextView
中更改文字颜色。我在选定的文本视图文本上获得NSRange
但无法使用此代码更改其颜色。
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:10.0/255.0 green:15.0/255.0 blue:5.0/255.0 alpha:1.0] range:range1];
有没有办法在文本视图中更改抽头颜色更改?
答案 0 :(得分:1)
我希望,这段代码可以帮到你:) 在我的场景中,我通过点击uiButton更改选定的textColor,您可以尝试这种方式。
// When text is tapped or selected by user we can change the
- (IBAction)applyBlueColor:(id)sender {
// getting textRange
NSRange textRange = [_textView selectedRange];
NSDictionary *attributeDictionary = [_textView.textStorage attributesAtIndex:textRange.location
effectiveRange:nil];
if ([attributeDictionary objectForKey:NSForegroundColorAttributeName] == nil ||
[attributeDictionary objectForKey:NSForegroundColorAttributeName] != [UIColor blackColor]) {
// Setting blue color to my selected text.
NSDictionary *colorDictionary = @{NSForegroundColorAttributeName: [UIColor blueColor]};
[_textView.textStorage beginEditing];
[_textView.textStorage setAttributes:colorDictionary range:textRange];
[_textView.textStorage endEditing];
}
}
答案 1 :(得分:0)
你好每个人都发表了我的答案。我希望它对其他人enter code here
-(void)textTapped:(UITapGestureRecognizer *)recognizer
{
NSMutableAttributedString *attributedStringText = [[NSMutableAttributedString alloc]initWithString:txtView.text];
UITextView *textView = (UITextView *)recognizer.view;
NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [recognizer locationInView:textView];
location.x -= textView.textContainerInset.left;
location.y -= textView.textContainerInset.top;
// Get character Index.
NSInteger characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];
if (characterIndex < textView.textStorage.length)
{
// Enumerate string and get word from character index.
[txtView.text enumerateSubstringsInRange:NSMakeRange(0, textView.textStorage.length)options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if (NSLocationInRange(characterIndex, enclosingRange)) {
// Do your thing with the word, at range 'enclosingRange'
//[mutableAttributedString setTextColor:[UIColor redColor] range:NSMakeRange(range.location, [word1 length])];
// Change color of text.
//[attributedStringText addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0] range:NSMakeRange(enclosingRange.location,[word1 length])];
NSLog(@"%@",textView.tintColor);
NSLog(@"%@",);
[attributedStringText addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(enclosingRange.location,[word1 length])];
[textView setAttributedText:attributedStringText];
*stop = YES;
}
}];
}
}