簡體   English   中英

如何在UITextView中為文本着色

[英]How to color text in UITextView

我在視圖控制器上有四個按鈕和一個文本視圖。 這五個按鈕有顏色,例如紅色,黃色,綠色,藍色和黑色。

當用戶開始鍵入而不按下那些按鈕時,鍵入的文本視圖的顏色應該具有黑色文本。 如果用戶按下紅色按鈕,則該點的文本顏色應為紅色,直到用戶按下任何其他彩色按鈕。

在此輸入圖像描述

這個怎么做 ? 我已經按照本教程https://www.objc.io/issues/5-ios7/getting-to-know-textkit/

但不知道如何將其定制為我想要實現的目標。

您需要使用NSAttributedString類。

let defaultAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize()),
                         NSForegroundColorAttributeName: UIColor.blackColor()]
let text = "this text is red and yellow"
let str = NSMutableAttributedString(string: text, attributes: defaultAttributes)
str.setAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: (text as NSString).rangeOfString("red"))
str.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: (text as NSString).rangeOfString("yellow"))
textView.attributedText = str

您可以使用NSMutableAttributedString來實現這一點。 這個想法是以下(我沒有測試它,只是手寫在這里寫):

NSString *str = @"stackoverflow";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];

// Set foreground color of "stack" substring in our string to red
[attributedString addAttribute:NSForegroundColorAttributeName
  value:[UIColor redColor];
  range:NSMakeRange(0, 5)];

使用此方法,您可以實現您希望將顏色應用於文本中所需范圍的內容。

您可以將屬性文本設置為UILabel,如下所示:

yourLabel.attributedText = attributedString

以下是我如何繼續,如果它可以幫助您:

1- add one property to retain current Color  and initialize it with black color 

 @property (nonatomic, retain) UIColor *curColor;//in your interface declaration

self.curColor = [UIColor blackColor];//Init it in Viewdidload for example

2-實現UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

    NSAttributedString *currentText = self.Textview.attributedText;//To store current text and its attributs
    NSAttributedString *newOneText = [[NSAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:self.curColor}];//for the new text with selected color

    NSMutableAttributedString  *shouldDisplayText = [[NSMutableAttributedString alloc] initWithAttributedString: currentText];

    [shouldDisplayText appendAttributedString: newOneText];// add old and new text

    self.Textview.attributedText = shouldDisplayText;//set it ton control


    return NO;
}

3-添加IBAction以改變顏色=>

 - (IBAction) redColorClicked
    {
     self.curColor = [UIColor colorWithRed:1.0f green: 0.0f blue:0.0f alpha:1.0f];
   }

- (IBAction) blueColorClicked
        {
         self.curColor = [UIColor colorWithRed:0.0f green: 0.0f blue:1.0f alpha:1.0f];
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM