UILabel с текстом двух разных цветов
89025 просмотра
20 ответа
Я хочу отобразить строку, как это в UILabel
:
Есть 5 результатов.
Где число 5 красного цвета, а остальная часть строки черная.
Как я могу сделать это в коде?
Автор: Peter Источник Размещён: 12.09.2019 01:39Ответы (20)
219 плюса
Способ сделать это состоит в NSAttributedString
следующем:
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc]
initWithAttributedString: label.attributedText];
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(10, 1)];
[label setAttributedText: text];
Я создал UILabel
расширение, чтобы сделать это .
57 плюса
Я сделал это, создав 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
}
SWIFT 4 @ kj13 Спасибо за уведомление
// If no text is send, then the style will be applied to full text
func setColorForText(_ textToFind: String?, with color: UIColor) {
let range:NSRange?
if let text = textToFind{
range = self.mutableString.range(of: text, options: .caseInsensitive)
}else{
range = NSMakeRange(0, self.length)
}
if range!.location != NSNotFound {
addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range!)
}
}
Я провел больше экспериментов с атрибутами и ниже приведены результаты, вот ИСТОЧНИК
Вот результат
Автор: anoop4real Размещён: 30.09.2015 10:3125 плюса
Ну вот
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;
Автор: Hardik Mamtora
Размещён: 24.04.2015 09:50
15 плюса
Swift 4
// An attributed string extension to achieve colors on text.
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, 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.setColor(color: UIColor.red, forText: "5")
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
Результат
Swift 3
func setColoredLabel() {
var string: NSMutableAttributedString = NSMutableAttributedString(string: "redgreenblue")
string.setColor(color: UIColor.redColor(), forText: "red")
string.setColor(color: UIColor.greenColor(), forText: "green")
string.setColor(color: UIColor.blueColor(, forText: "blue")
mylabel.attributedText = string
}
func setColor(color: UIColor, forText stringValue: String) {
var range: NSRange = self.mutableString.rangeOfString(stringValue, options: NSCaseInsensitiveSearch)
if range != nil {
self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
}
Результат:
12 плюса
//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;
Автор: raju dontiboina
Размещён: 16.03.2016 10:23
6 плюса
Начиная с iOS 6 , UIKit поддерживает отрисовку приписанных строк, поэтому расширение или замена не требуются.
От UILabel
:
@property(nonatomic, copy) NSAttributedString *attributedText;
Вам просто нужно создать свой NSAttributedString
. Есть два основных способа:
Добавляйте фрагменты текста с одинаковыми атрибутами - для каждой части создайте один
NSAttributedString
экземпляр и добавьте их к одномуNSMutableAttributedString
Создайте атрибутивный текст из простой строки, а затем добавьте атрибутированный для заданных диапазонов - найдите диапазон вашего числа (или чего-либо еще) и примените к нему другой цветовой атрибут.
6 плюса
Анупы отвечают быстро. Может быть повторно использован из любого класса.
В быстром файле
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;
Автор: Deepak Thakur
Размещён: 25.02.2016 09:16
4 плюса
Наличие UIWebView или нескольких UILabel может считаться излишним для этой ситуации.
Мое предложение было бы использовать TTTAttributedLabel, который является заменой для UILabel, который поддерживает NSAttributedString . Это означает, что вы можете очень легко применять разные стили к различным диапазонам в строке.
Автор: Mic Pringle Размещён: 28.06.2011 09:504 плюса
Для отображения короткого отформатированного текста, который не нужно редактировать, Core Text - это то, что нужно. Существует несколько проектов с открытым исходным кодом для меток, которые используют NSAttributedString
Core Core для рендеринга. См. CoreTextAttributedLabel или OHAttributedLabel, например.
3 плюса
JTAttributedLabel (by mystcolor) позволяет использовать поддержку атрибутивных строк в UILabel под iOS 6 и в то же время его класс JTAttributedLabel под iOS 5 через его JTAutoLabel.
Автор: Johan Kool Размещён: 28.03.2013 05:592 плюса
NSAttributedString
это путь На следующий вопрос есть отличный ответ, который показывает вам, как это сделать. Как вы используете NSAttributedString?
2 плюса
Есть решение 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)
Автор: Kevin ABRIOUX
Размещён: 03.10.2016 07:13
2 плюса
В моем ответе также есть возможность закрасить все вхождения текста, а не только одно его вхождение: «ва ба ва ба дабдуб», вы можете раскрасить все вхождения ва, а не только первое вхождение, как принятый ответ.
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 setColorForAllOccuranceOfText(_ textToFind: String, with color: UIColor) {
let inputLength = self.string.count
let searchLength = textToFind.count
var range = NSRange(location: 0, length: self.length)
while (range.location != NSNotFound) {
range = (self.string as NSString).range(of: textToFind, options: [], range: range)
if (range.location != NSNotFound) {
self.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
}
}
}
}
Теперь вы можете сделать это:
let message = NSMutableAttributedString(string: "wa ba wa ba dubdub")
message.setColorForText(subtitle, with: UIColor.red)
// or the below one if you want all the occurrence to be colored
message.setColorForAllOccuranceOfText("wa", with: UIColor.red)
// then you set this attributed string to your label :
lblMessage.attributedText = message
Автор: Alsh compiler
Размещён: 19.07.2018 10:43
1 плюс
Для пользователей 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;
}
Автор: Craig Champion
Размещён: 30.01.2017 02:17
1 плюс
Swift 4 и выше: Вдохновленный решением anoop4real , вот расширение String, которое можно использовать для создания текста с двумя разными цветами.
extension String {
func attributedStringForPartiallyColoredText(_ textToFind: String, with color: UIColor) -> NSMutableAttributedString {
let mutableAttributedstring = NSMutableAttributedString(string: self)
let range = mutableAttributedstring.mutableString.range(of: textToFind, options: .caseInsensitive)
if range.location != NSNotFound {
mutableAttributedstring.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
return mutableAttributedstring
}
}
Следующий пример меняет цвет звездочки на красный, сохраняя оригинальный цвет метки для оставшегося текста.
label.attributedText = "Enter username *".attributedStringForPartiallyColoredText("*", with: #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))
Автор: Maverick
Размещён: 10.12.2017 06:10
0 плюса
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
}
}
Автор: Dipak Panchasara
Размещён: 04.10.2016 12:57
0 плюса
Моим собственным решением был создан метод, подобный следующему:
-(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; }
Он работал только с одним другим цветом в том же тексте, но вы можете легко адаптировать его к большему количеству цветов в одном предложении.
Автор: shontauro Размещён: 05.11.2016 04:580 плюса
Используя приведенный ниже код, вы можете установить несколько цветов на основе слова.
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];
}
Автор: Hari c
Размещён: 06.06.2017 10:48
0 плюса
SwiftRichString
работает отлично! Вы можете использовать +
для объединения двух приписанных строк
0 плюса
В моем случае я использую Xcode 10.1. В Интерфейсном Разработчике есть возможность переключения между обычным текстом и Приписанным текстом в тексте Метки
Надеюсь, что это может помочь кому-то еще ..!
Автор: BharathRao Размещён: 05.08.2019 11:11Вопросы из категории :
- ios Приложение для iPhone в ландшафтном режиме, системы 2008
- ios Как мне дать моим веб-сайтам значок для iPhone?
- ios Как программно отправить смс на айфон?
- ios Как я могу разработать для iPhone, используя машину для разработки Windows?
- objective-c Открытие нестандартного URL в приложении Какао
- objective-c Каков наилучший способ перетащить NSMutableArray?
- swift Как я могу программным образом определить, работает ли мое приложение в симуляторе iphone?
- swift iOS: Convert UTC NSDate to local Timezone
- swift Как установить цель и действие для UIBarButtonItem во время выполнения
- swift Жирный и не жирный текст в одном UILabel?
- uilabel Несколько строк текста в UILabel
- uilabel Как создать NSMutableArray из UILabels?
- uilabel Выровнять текст по вертикали внутри UILabel
- uilabel Создавать привязанные «ссылки» в NSAttributedString UILabel?
- textcolor Как вы используете NSAttributedString?
- textcolor Текст UILabel с несколькими цветами шрифтов
- textcolor UILabel с текстом двух разных цветов
- textcolor Можно ли изменить цвет текста в строке на несколько цветов в Java?