Я пытаюсь установить цвет фона/выделить только текст в UILabel
. Проблема заключается в том, что разрывы строк и пробелы, добавленные в UILabel
, чтобы сохранить текст в центре, также выделяются.
Обратите внимание на интервал перед тем, как подсвечивается последняя строка в UILabel
. Также выделяются начало и конец любых новых строк.
Я создаю пример выше со следующим кодом:
-(void)createSomeLabel {
// Create and position my label
UILabel *someLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,
0,
self.view.frame.size.width - 40,
self.view.frame.size.height - 300)];
someLabel.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
someLabel.textAlignment = NSTextAlignmentCenter;
someLabel.textColor = [UIColor whiteColor];
someLabel.lineBreakMode = NSLineBreakByWordWrapping;
someLabel.numberOfLines = 0;
[self.view addSubview:someLabel];
// This string will be different lengths all the time
NSString *someLongString = @"Here is a really long amount of text that is going to wordwrap/line break and I don't want to highlight the spacing. I want to just highlight the words and a single space before/after the word";
// Create attributed string
NSMutableAttributedString *someLongStringAttr=[[NSMutableAttributedString alloc] initWithString:someLongString attributes:nil];
// Apply background color
[someLongStringAttr addAttribute:NSBackgroundColorAttributeName
value:[UIColor colorWithWhite:0 alpha:0.25]
range:NSMakeRange(0, someLongStringAttr.length)];
// Set text of label
someLabel.attributedText = someLongStringAttr;
}
Выход, который я хотел бы достичь, состоит в том, чтобы выделить только текст и пробелы между словами, если есть только одно пространство. Длина текста и размер UILabel
будут постоянно отличаться, поэтому жесткое кодирование не является вариантом.