Преобразование строки Html в строку Attributed и присвоение textview, получая дополнительное пространство - PullRequest
0 голосов
/ 09 апреля 2020

Я провел более 8 часов, но не смог решить мою проблему. Мой код, как показано ниже:

let sampleHTML = "<p><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" style=\"\" size=\"1\"><b style=\"\">1. GPS must be turned on<\/b>&nbsp;to locate panel GP clinics within 1 km from your location.<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">2.&nbsp;You can do a wildcard search based on “Clinic Name” or “Road Name”.<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">3. The top right corner&nbsp;shows the tip of a highlighter which is a <b>Filter<\/b>&nbsp;to find another Panel type eg. TCM or Specialist Panel (where applicable).<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">4. When the search is done, click on your desired panel clinic and you can<\/font><\/span><\/p><blockquote style=\"margin: 0 0 0 40px; border: none; padding: 0px;\"><p class=\"p2\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><b><font color=\"#000000\" size=\"1\">(a) View Clinic Operating hours<\/font><\/b><\/span><\/p><\/blockquote><blockquote style=\"margin: 0 0 0 40px; border: none; padding: 0px;\"><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><b style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">(b) Call the clinic<\/font><\/b><\/p><\/blockquote><blockquote style=\"margin: 0 0 0 40px; border: none; padding: 0px;\"><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><b style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">(c) Get Direction to the panel clinic (GPS must be turned on)<\/font><\/b><\/p><\/blockquote><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">5.If <b>GPS is not turned on<\/b>, you can still access to 4a and 4b for your selected panel clinic.<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><b><i style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">Important Notice<\/font><\/i><\/b><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">(1) <i>*Last Clinic Registration is<\/i>&nbsp;<b>30 Minutes before closing time or earlier<\/b> if the number of patients’ registration exceeded the capacity that the attending doctor and clinic staff can handle that goes beyond the clinic normal operating hours.<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">(2) <b>Surcharge<\/b> will be imposed on members for visit <i>on or after *Last Clinic Registration<\/i>.<\/font><\/span><\/p><p class=\"p1\" style=\"margin-right: 0px; margin-left: 0px; font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; line-height: normal; font-family: Menlo;\"><span style=\"background-color: rgb(255, 255, 255);\"><font color=\"#000000\" size=\"1\">(3) <b>Operating hours<\/b> are indicative. Please call the clinic before visiting as clinics’ operating hours may change without prior notice.<\/font><\/span><\/p><div><font color=\"rgba(255, 255, 255, 0.850980392156863)\" face=\"Menlo\" size=\"1\"><br><\/font><\/div><div><font size=\"1\"><img src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAAAKMWlDQ1BJQ0MgUHIAQAAAAAICAEAAAAACAgBAAAAAAgIAQAAAAAICD\/H8\/yGKggh8zsAAAAAElFTkSuQmCC\"><\/font><font color=\"rgba(255, 255, 255, 0.850980392156863)\" face=\"Menlo\"><span style=\"font-size: 1px;\"><br><\/span><\/font><\/div>"

Преобразование html в расширение приписанной строки, как показано ниже:

    extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)

            //[.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue]
        } catch {
            return NSAttributedString()
        }
    }

    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }   
}

Загрузка приписанного текста в текстовое представление, как показано ниже:

cell.txtViewHTML.attributedText = sampleHTML.htmlToAttributedString

Вывод экрана, как показано ниже:

Getting extra spacing in between, if i load same in webview it is looking fine

Я считаю, что что-то не так в моем коде, может кто-нибудь, пожалуйста, помогите.

Заранее спасибо .

1 Ответ

2 голосов
/ 09 апреля 2020

Я внес несколько изменений в ваш HTML код:

let sampleHTML = "<p><b>1. GPS must be turned on</b>&#160;to locate panel GP clinics within 1 km from your location.</p><p><b>2.</b>&#160;You can do a wildcard search based on &#8220;Clinic Name&#8221; or &#8220;Road Name&#8221;.</p><p><b>3. The top right corner</b>&#160;shows the tip of a highlighter which is a&#160;<b>Filter</b>&#160;to find another Panel type eg. TCM or Specialist Panel (where applicable).</p><p>4. When the search is done, click on your desired panel clinic and you can<ol type=\"a\"><li><b>View Clinic Operating hours</b></li><li><b>Call the clinic</b></li><li><b>Get Direction to the panel clinic (GPS must be turned on).</b></li></ol></p><p><b>5.</b>&#160;If&#160;<b>GPS is not turned on</b>, you can still access to S/no 4a and 4b for your selected panel clinic.</p><h1><p><i><font size=\"3\">Important Notice</font></i></h1><ol type=\"a\"><li><i>*Last Clinic Registration is&#160;</i><b>30 Minutes before closing time or earlier</b>if the number of patients&#8217; registration exceeded the capacity that the attending doctor and clinic staff can handle that goes beyond the clinic normal operating hours.</li><li><b>Surcharge&#160;</b>will be imposed on members for visit&#160;<i>on or after *Last Clinic Registration.</i></li><li><b>Operating hours&#160;</b>are indicative. Please call the clinic before visiting as clinics&#8217; operating hours may change without prior notice.</li></ol></p>"

.

Пример вывода из StackOverflow "Blockquotes"

1. GPS должен быть включен , чтобы определить местонахождение групповых клиник в пределах 1 км от вашего местоположения.

2. Вы можете выполнить поиск по шаблону, основываясь на «Clini c Name» или «Название дороги».

3. В верхнем правом углу показан кончик маркера, который представляет собой Filter для поиска другого типа панели, например. TCM или специализированная группа (где применимо).

4. Когда поиск будет завершен, нажмите на желаемую панель clini c, и вы сможете

Просмотреть Clini c Часы работы Позвонить на clini c Получить направление на панель клини c (GPS должен быть включен).

5. Если GPS не включен , вы все еще можете получить доступ к S / no 4a и 4b для выбранной панели clini c.

Важное замечание

* Last Clini c Регистрация 30 минут до закрытия или раньше , если количество регистраций пациентов превысило возможности, которые лечащий врач и клини c Персонал может справиться с тем, что выходит за рамки обычного рабочего времени клини c. Доплата будет взиматься с участников за посещение во время или после * последней регистрации в клинике. Часы работы являются ориентировочными. Пожалуйста, позвоните в клини c до посещения, так как часы работы клиник могут измениться без предварительного уведомления.

Пример вывода в симуляторе: (Пожалуйста, игнорируйте фон скриншота) enter image description here

Дайте мне знать, если вам нужна помощь по части HTML.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...