UILabel с текстом двух разных цветов
Я хочу отобразить такую строку в UILabel
:
Есть 5 результатов.
Где число 5 красного цвета, а остальная часть строки – черная.
- Проблема с UICollectionView: не отображает метки всех его ячеек
- Проверить усечение в UILabel - iOS, Swift
- Отключить кнопку, основанную на значении метки
- Цвет текста текстовой метки UITableViewCell
- Изменение размера UILabel не совсем работает
Как это сделать в коде?
- Как настроить меток labelMaxLayoutWidth для автоматического программирования?
- Изменение текста UILabel задерживается, но почему?
- Устройство распознавания жестов не работает по какой-либо причине, на iphone
- Как достичь фонового изображения в UILabel, как в pic?
- UILabel с заданной прозрачностью, но textLabel должен быть непрозрачным
- Как проверить, был ли затронут текст UILabel?
- Сделать UILabel похожим на CSS-дисплей: inline
- Сохраняйте UILabel с центром в UIView, когда изменяется длина символов. iOS, цель C
Способ сделать это – использовать NSAttributedString
следующим образом:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: label.attributedText]; [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 1)]; [label setAttributedText: text];
Для этого я создал расширение UILabel
.
Я сделал это, создав category
для NSMutableAttributedString
-(void)setColorForText:(NSString*) textToFind withColor:(UIColor*) color { NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch]; if (range.location != NSNotFound) { [self addAttribute:NSForegroundColorAttributeName value:color range:range]; } }
Используйте его как
- (void) setColoredLabel { NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Here is a red blue and green text"]; [string setColorForText:@"red" withColor:[UIColor redColor]]; [string setColorForText:@"blue" withColor:[UIColor blueColor]]; [string setColorForText:@"green" withColor:[UIColor greenColor]]; mylabel.attributedText = string; }
SWIFT 3
extension NSMutableAttributedString{ func setColorForText(_ textToFind: String, with color: UIColor) { let range = self.mutableString.range(of: textToFind, options: .caseInsensitive) if range.location != NSNotFound { addAttribute(NSForegroundColorAttributeName, value: color, range: range) } } }
ПРИМЕНЕНИЕ
func setColoredLabel() { let string = NSMutableAttributedString(string: "Here is a red blue and green text") string.setColorForText("red", with: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)) string.setColorForText("blue", with: #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)) string.setColorForText("green", with: #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)) mylabel.attributedText = string }
и вот результат
Ну вот
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:lblTemp.text]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)]; lblTemp.attributedText = string;
//NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' "; NSString *myString = @"Not a member?signin"; //Create mutable string from original one NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString]; //Fing range of the string you want to change colour //If you need to change colour in more that one place just repeat it NSRange range = [myString rangeOfString:@"signin"]; [attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range]; //Add it to the label - notice its not text property but it's attributeText _label.attributedText = attString;
Начиная с iOS 6 , UIKit поддерживает рисование присваиваемых строк, поэтому не требуется расширение или замена.
От UILabel
:
@property(nonatomic, copy) NSAttributedString *attributedText;
Вам просто нужно создать NSAttributedString
. Существуют два способа:
-
Добавьте фрагменты текста с одинаковыми атрибутами – для каждой части создайте один экземпляр
NSAttributedString
и добавьте их в однуNSMutableAttributedString
-
Создайте атрибутный текст из простой строки, а затем добавьте атрибут для заданных диапазонов – найдите диапазон вашего номера (или что-то еще) и примените к нему другой атрибут цвета.
Anups отвечает быстрым. Может использоваться повторно из любого класса.
В быстром файле
extension NSMutableAttributedString { func setColorForStr(textToFind: String, color: UIColor) { let range = self.mutableString.rangeOfString(textToFind, options:NSStringCompareOptions.CaseInsensitiveSearch); if range.location != NSNotFound { self.addAttribute(NSForegroundColorAttributeName, value: color, range: range); } } }
В контроллере некоторых представлений
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.labelShopInYourNetwork.text!); attributedString.setColorForStr("YOUR NETWORK", color: UIColor(red: 0.039, green: 0.020, blue: 0.490, alpha: 1.0)); self.labelShopInYourNetwork.attributedText = attributedString;
Наличие UIWebView или более одного UILabel можно считать излишним для этой ситуации.
Мое предложение было бы использовать TTTAttributedLabel, который является заменой замены для UILabel, которая поддерживает NSAttributedString . Это означает, что вы можете очень легко применять разные стили к различным диапазонам в строке.
Для отображения короткого отформатированного текста, который не требуется редактировать, Core Text – это путь. Существует несколько проектов с открытым исходным кодом для ярлыков, которые используют NSAttributedString
и Core Text для рендеринга. См. Например, CoreTextAttributedLabel или OHAttributedLabel .
JTAttributedLabel (by mystcolor) позволяет использовать поддержку атрибутов string в UILabel под iOS 6 и в то же время класс JTAttributedLabel в iOS 5 через JTAutoLabel.
NSAttributedString
– это путь. Следующий вопрос имеет отличный ответ, который показывает вам, как это сделать. Как вы используете NSAttributedString
Существует решение Swift 3.0
extension UILabel{ func setSubTextColor(pSubString : String, pColor : UIColor){ let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!); let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive) if range.location != NSNotFound { attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range); } self.attributedText = attributedString } }
И есть пример вызова:
let colorString = " (string in red)" self.mLabel.text = "classic color" + colorString self.mLabel.setSubTextColor(pSubString: colorString, pColor: UIColor.red)
Swift 4
// An attributed string extension to achieve colors on text. extension NSMutableAttributedString { func setColorForText(textToFind: String, withColor color: UIColor) { let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive) self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) } } // Try it with label let label = UILabel() label.frame = CGRect(x: 70, y: 100, width: 260, height: 30) let stringValue = "There are 5 results." let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) attributedString.setColorForText(textToFind: "5", withColor: UIColor.red) label.font = UIFont.systemFont(ofSize: 26) label.attributedText = attributedString self.view.addSubview(label)
результат
Swift 3
func setColoredLabel() { var string: NSMutableAttributedString = NSMutableAttributedString(string: "redgreenblue") string.setColorForText("red", withColor: UIColor.redColor()) string.setColorForText("green", withColor: UIColor.greenColor()) string.setColorForText("blue", withColor: UIColor.blueColor()) mylabel.attributedText = string } func setColorForText(textToFind: String, withColor color: UIColor) { var range: NSRange = self.mutableString.rangeOfString(textToFind, options: NSCaseInsensitiveSearch) if range != nil { self.addAttribute(NSForegroundColorAttributeName, value: color, range: range) } }
Результат:
extension UILabel{ func setSubTextColor(pSubString : String, pColor : UIColor){ let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!); let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive) if range.location != NSNotFound { attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range); } self.attributedText = attributedString } }
Моему собственному решению был создан такой метод, как следующий:
-(void)setColorForText:(NSString*) textToFind originalText:(NSString *)originalString withColor:(UIColor*)color andLabel:(UILabel *)label{ NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:originalString]; NSRange range = [originalString rangeOfString:textToFind]; [attString addAttribute:NSForegroundColorAttributeName value:color range:range]; label.attributedText = attString; if (range.location != NSNotFound) { [attString addAttribute:NSForegroundColorAttributeName value:color range:range]; } label.attributedText = attString; }
Он работал только с одним цветом в одном и том же тексте, но вы можете легко адаптировать его к большему количеству цветов в том же предложении.
Для пользователей Xamarin у меня есть статический метод C #, в котором я передаю массив строк, массив UIColours и массив UIFonts (они должны соответствовать по длине). Присвоенная строка затем возвращается обратно.
видеть:
public static NSMutableAttributedString GetFormattedText(string[] texts, UIColor[] colors, UIFont[] fonts) { NSMutableAttributedString attrString = new NSMutableAttributedString(string.Join("", texts)); int position = 0; for (int i = 0; i < texts.Length; i++) { attrString.AddAttribute(new NSString("NSForegroundColorAttributeName"), colors[i], new NSRange(position, texts[i].Length)); var fontAttribute = new UIStringAttributes { Font = fonts[i] }; attrString.AddAttributes(fontAttribute, new NSRange(position, texts[i].Length)); position += texts[i].Length; } return attrString; }
Используя приведенный ниже код, вы можете установить несколько цветов на основе слова.
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil]; NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init]; for (NSString * str in array) { NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}]; [attStr appendAttributedString:textstr]; } UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)]; lab.attributedText = attStr; [self.view addSubview:lab]; -(UIColor *) getRandomColor { CGFloat redcolor = arc4random() % 255 / 255.0; CGFloat greencolor = arc4random() % 255 / 255.0; CGFloat bluencolor = arc4random() % 255 / 255.0; return [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0]; }