NSAttributedString每行的新颜色(来自数组的字符串)

时间:2015-07-19 16:16:27

标签: xcode colors nsarray nsattributedstring

我正在尝试在UITextView中显示存储在数组中的彩色文本。 NSAttributedStrings通常有效,但我想在新行中显示每个objectAtIndex项并更改文本的颜色。这是我的代码,它显示奇怪的输出:

<?php
$options = array(
    "header" => "assets/config_header.php", 
    "color" => "assets/config_header5.php", 
    "headline" => "assets/config_header1.php", 
    "color1" => "assets/config_header6.php", 
    "subhead" => "assets/config_header2.php", 
    "color2" => "assets/config_header7.php", 
    "prodname" => "assets/config_header3.php", 
    "vivid" => "assets/config_header3.php"
);

foreach ($options as $key => $file) {
    if($_POST[$key]) {
        if(isset($_POST[$key]) && trim($_POST[$key]) != ""){
            $fp = fopen($file, 'w');
            fwrite($fp, '<?php');
            fwrite($fp, ' ');
            fwrite($fp, '$' . $key . ' = "'.trim($_POST[$key]).'";');
            fwrite($fp, ' ');
            fwrite($fp, '?>');
            fclose($fp);
            break;
        }
    }
}
  1. 循环通过一个数组来检查标志&#34; - &#34; &安培; &#34; +&#34;
  2. 根据&#34; - &#34;分配颜色; &安培; &#34; +&#34;
  3. 在UITextView中显示属性字符串
  4. 实际UITextView中的奇怪输出是:

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    
    for (NSString *str in self.tvInputArray){
    
        if ([str containsString:@"-"] ) {
    
            NSAttributedString *atrString = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n",str] attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
    
            [attributedString appendAttributedString:atrString];
        }
    
        else if ([str containsString:@"+"] ) {
    
            NSAttributedString *atrString2 = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n",str] attributes:@{NSForegroundColorAttributeName: [UIColor blueColor]}];
    
            [attributedString appendAttributedString:atrString2];
        }
    }
    
    [selectedItemsTV setText:[NSString stringWithFormat:@"%@", attributedString]];
    

    有人能指出正确的方向吗?

1 个答案:

答案 0 :(得分:0)

知道了,我忘了把它作为属性字符串传递给UITextView:

 [selectedItemsTV setAttributedText:attributedString];

希望这会对某人有所帮助