Если вы показываете дочернюю форму как модальное диалоговое окно, вы можете установить свойство DialogResult дочерней формы со значением из перечисления DialogResult, которое, в свою очередь, скрывает модальное диалоговое окно и возвращает управление вызывающей форме. В это время родитель может получить данные дочерней формы, чтобы получить необходимую информацию.
Для получения дополнительной информации проверьте эту ссылку: http://msdn.microsoft.com/en-us/library/ system.windows.forms.form.dialogresult (v = vs.110) .aspx [/ д2]
SetAttributes сбрасывает все атрибуты из HTML. Я написал метод расширения, чтобы избежать этого:
Swift 4
public convenience init?(HTMLString html: String, font: UIFont? = nil) throws {
let options : [NSAttributedString.DocumentReadingOptionKey : Any] =
[NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]
guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}
if let font = font {
guard let attr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}
var attrs = attr.attributes(at: 0, effectiveRange: nil)
attrs[NSAttributedStringKey.font] = font
attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
self.init(attributedString: attr)
} else {
try? self.init(data: data, options: options, documentAttributes: nil)
}
}
Тестовый образец:
let html = "<html><body><h1 style=\"color:red;\">html text here</h1></body></html>"
let font = UIFont.systemFont(ofSize: 16)
var attr = try NSMutableAttributedString(HTMLString: html, font: nil)
var attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7ff19fd0a530> font-family: "TimesNewRomanPS-BoldMT"; font-weight: bold; font-style: normal; font-size: 24.00pt
attr = try NSMutableAttributedString(HTMLString: html, font: font)
attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7f8c0cc04620> font-family: ".SFUIText"; font-weight: normal; font-style: normal; font-size: 16.00pt
версия Swift 3 моего предыдущего (Swift 4) решения
extension NSAttributedString {
convenience init(htmlString html: String, font: UIFont? = nil, useDocumentFontSize: Bool = true) throws {
let options: [String : Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
let data = html.data(using: .utf8, allowLossyConversion: true)
guard (data != nil), let fontFamily = font?.familyName, let attr = try? NSMutableAttributedString(data: data!, options: options, documentAttributes: nil) else {
try self.init(data: data ?? Data(html.utf8), options: options, documentAttributes: nil)
return
}
let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize
let range = NSRange(location: 0, length: attr.length)
attr.enumerateAttribute(NSFontAttributeName, in: range, options: .longestEffectiveRangeNotRequired) { attrib, range, _ in
if let htmlFont = attrib as? UIFont {
let traits = htmlFont.fontDescriptor.symbolicTraits
var descrip = htmlFont.fontDescriptor.withFamily(fontFamily)
if (traits.rawValue & UIFontDescriptorSymbolicTraits.traitBold.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitBold)!
}
if (traits.rawValue & UIFontDescriptorSymbolicTraits.traitItalic.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitItalic)!
}
attr.addAttribute(NSFontAttributeName, value: UIFont(descriptor: descrip, size: fontSize ?? htmlFont.pointSize), range: range)
}
}
self.init(attributedString: attr)
}
}
'DocumentReadingOptionKey' is unavailable in Swift
. С тех пор они заменили его чем-то другим? Поиск в Google не появляется.
– keverly
20 February 2018 в 00:00
let font = UIFont(name: fontName, size: fontSize)
textAttributes[NSFontAttributeName] = font
self.attributedText = NSAttributedString(string: self.text, attributes: textAttributes)
Что вы хотите сделать, в основном, превратить NSAttributedString в NSMutableAttributedString.
let attributedT = // ... attributed string
let mutableT = NSMutableAttributedString(attributedString:attributedT)
Теперь вы можете вызвать addAttributes
, чтобы применить атрибуты, такие как другой шрифт, в любом желаемом диапазоне, например, все это.
Однако, к сожалению, шрифт без символической черты, такой как курсив, представляет собой другой шрифт из шрифта с этим символическим признаком. Поэтому вам понадобится утилита, которая копирует существующие символические черты из шрифта и применяет их к другому шрифту:
func applyTraitsFromFont(_ f1: UIFont, to f2: UIFont) -> UIFont? {
let t = f1.fontDescriptor.symbolicTraits
if let fd = f2.fontDescriptor.withSymbolicTraits(t) {
return UIFont.init(descriptor: fd, size: 0)
}
return nil
}
Хорошо, поэтому, вооружившись этой утилитой, давайте попробуем. Я начну с простого HTML-кода и преобразую его в атрибутную строку, как вы это делаете:
let html = "<p>Hello <i>world</i>, hello</p>"
let data = html.data(using: .utf8)!
let att = try! NSAttributedString.init(
data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
let matt = NSMutableAttributedString(attributedString:att)
Как вы можете видеть, я перешел в NSMutableAttributedString, как я вам посоветовал. Теперь я буду циклически выполнять стили в терминах шрифта, изменяясь на другой шрифт, используя мою утилиту для применения существующих признаков:
matt.enumerateAttribute(
NSFontAttributeName,
in:NSMakeRange(0,matt.length),
options:.longestEffectiveRangeNotRequired) { value, range, stop in
let f1 = value as! UIFont
let f2 = UIFont(name:"Georgia", size:20)!
if let f3 = applyTraitsFromFont(f1, to:f2) {
matt.addAttribute(
NSFontAttributeName, value:f3, range:range)
}
}
Вот результат:
Очевидно, вы могли бы настроить эту процедуру еще более сложной, в зависимости от ваших потребностей в дизайне.
addAttributes
. Исправлено. Спасибо, что поймал это.
– matt
1 January 2017 в 04:26