Мне нужно найти некоторые строки и установить некоторые атрибуты до слияния строк, поэтому с помощью NSStrings → Concatenate them → make NSAttributedString не является опцией, есть ли способ связать атрибут attribringString с другим атрибутомString?
Как я могу объединить NSAttributedStrings?
Ответ 1
Я бы порекомендовал вам использовать одну изменяемую атрибутную строку, предложенную @Linuxios, и вот еще один пример этого:
NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];
NSString *plainString = // ...
NSDictionary *attributes = // ... a dictionary with your attributes.
NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:plainString attributes:attributes];
[mutableAttString appendAttributedString:newAttString];
Однако, только для того, чтобы получить все варианты, вы также можете создать одну изменяемую атрибутную строку, выполненную из форматированной NSString, содержащей уже введенные строки. Затем вы можете использовать addAttributes: range:
для добавления атрибутов после факта в диапазоны, содержащие входные строки. Я рекомендую использовать прежний путь.
Ответ 2
Если вы используете Swift, вы можете просто перегрузить оператор +
, чтобы вы могли объединить их так же, как вы объединяете обычные строки:
// concatenate attributed strings
func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
{
let result = NSMutableAttributedString()
result.append(left)
result.append(right)
return result
}
Теперь вы можете объединить их, просто добавив их:
let helloworld = NSAttributedString(string: "Hello ") + NSAttributedString(string: "World")
Ответ 3
Swift 3: просто создайте NSMutableAttributedString и добавьте к ним приписанные строки.
let mutableAttributedString = NSMutableAttributedString()
let boldAttribute = [
NSFontAttributeName: UIFont(name: "GothamPro-Medium", size: 13)!,
NSForegroundColorAttributeName: Constants.defaultBlackColor
]
let regularAttribute = [
NSFontAttributeName: UIFont(name: "Gotham Pro", size: 13)!,
NSForegroundColorAttributeName: Constants.defaultBlackColor
]
let boldAttributedString = NSAttributedString(string: "Warning: ", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "All tasks within this project will be deleted. If you're sure you want to delete all tasks and this project, type DELETE to confirm.", attributes: regularAttribute)
mutableAttributedString.append(boldAttributedString)
mutableAttributedString.append(regularAttributedString)
descriptionTextView.attributedText = mutableAttributedString
swift5 upd:
let captionAttribute = [
NSAttributedString.Key.font: Font.captionsRegular,
NSAttributedString.Key.foregroundColor: UIColor.appGray
]
Ответ 4
Попробуйте следующее:
NSMutableAttributedString* result = [astring1 mutableCopy];
[result appendAttributedString:astring2];
Где astring1
и astring2
- NSAttributedString
s.
Ответ 5
Если вы используете Cocoapods, альтернатива обоим выше ответам, которые позволяют вам избежать изменчивости в вашем собственном коде, - использовать отличный NSAttributedString + CCLFormat на NSAttributedString
, который позволяет вам написать что-то вроде:
NSAttributedString *first = ...;
NSAttributedString *second = ...;
NSAttributedString *combined = [NSAttributedString attributedStringWithFormat:@"%@%@", first, second];
Конечно, он просто использует NSMutableAttributedString
под обложками.
У него также есть дополнительное преимущество - полноценная функция форматирования, поэтому он может делать намного больше, чем добавлять строки вместе.
Ответ 6
// Immutable approach
// class method
+ (NSAttributedString *)stringByAppendingString:(NSAttributedString *)append toString:(NSAttributedString *)string {
NSMutableAttributedString *result = [string mutableCopy];
[result appendAttributedString:append];
NSAttributedString *copy = [result copy];
return copy;
}
//Instance method
- (NSAttributedString *)stringByAppendingString:(NSAttributedString *)append {
NSMutableAttributedString *result = [self mutableCopy];
[result appendAttributedString:append];
NSAttributedString *copy = [result copy];
return copy;
}
Ответ 7
Вы можете попробовать SwiftyFormat Он использует следующий синтаксис
let format = "#{{user}} mentioned you in a comment. #{{comment}}"
let message = NSAttributedString(format: format,
attributes: commonAttributes,
mapping: ["user": attributedName, "comment": attributedComment])