iOS:如何通过HTML字符串在WkWebView中显示手风琴(Accordion) Swift

huangapple go评论74阅读模式
英文:

iOS : how to Display Accordion in WkWebView through HTML strings Swift

问题

I need to display accordion in WKWebView from the html string coming from API response like this.
iOS:如何通过HTML字符串在WkWebView中显示手风琴(Accordion) Swift
I already tried so many solutions in SO to do this but still not able to create it please share some some solution or code to display this as expected.
I am sharing my code

let fullDesc = responseDict?["description_middle"]?.string ?? ""
let htmlString:String! = fullDesc

self.detailWeb.loadHTMLString("<html><body><style>p{align-items:justify;justify-content:justify} h1, h2, h3, h4, h5, h6{font-size:20px; font-weight:bold;} </style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0,Proxima Nova-Regular\">\(htmlString!)</body></html>", baseURL: nil)

And here is the html string i got from the response

"description_middle": "{\"ac_title\":[\"When Should I take this Service?\",\"What benefits will I get by taking this onsite styling consultation service?\",\"Can I select a Fashion Stylist of my choice for this consultation?\",\"What Happens after I make the Payment?\"],\"ac_description\":[\"<p>You should take this Wardrobe Consultation Service if you are facing any of the following situations:</p>\\r\\n\\r\\n<ul>\\r\\n\\t<li>You are struggling to find clothes that fit and flatter your body type</li>\\r\\n\\t<li>You have a big event coming up and need help putting together the perfect outfit</li>\\r\\n\\t<li>you want to update your professional image and make a great first impression</li>\\r\\n\\t<li>you have a closet full of clothes but nothing to wear</li>\\r\\n\\t<li>you want to build a sustainable wardrobe that is both stylish and environmentally friendly</li>\\r\\n</ul>\\r\\n\",\"<p>Taking a Wardrobe Consultation Service brings you several benefits. Some of those benefits are given below:</p>\\r\\n\\r\\n<ul>\\r\\n\\t<li>Time and Convenience:&nbsp;A personal stylist saves your time and effort by doing the shopping, research and curating outfits for you, freeing up your own time to focus on other things.</li>\\r\\n\\t<li>Increased Confidence:&nbsp;A stylist can help you develop your personal style, which can lead to increased confidence in your appearance and self-esteem.</li>\\r\\n\\t<li>Expertise:&nbsp;Personal stylists have expertise in fashion, body shapes, color analysis and current trends, allowing you to benefit from their professional knowledge and advice.</li>\\r\\n\\t<li>Maximizing Wardrobe:&nbsp;A stylist can help you to get the most out of your existing wardrobe, by creating new outfits and suggesting key pieces to purchase, making the most of your investment.</li>\\r\\n\\t<li>Cost Savings:&nbsp;By investing in a personal stylist, you may save money in the long run by avoiding costly fashion mistakes, and making informed purchases that add value to your wardrobe.</li>\\r\\n</ul>\\r\\n\",\"<p>We would be introducing this feature in future. Until then, StyleBuddy will assign you the best available stylist at the time of your booking.</p>\\r\\n\",\"<p>Our Client Support Team will reach out to you to initiate your service sessions. You will be asked to update a Client Information Form, which is required for the Stylist to prepare for your Service. You can also call or WhatsAPP us on&nbsp;+91-00&nbsp;to enquire about&nbsp;your appointment. This service is available from 10 AM to 7 PM India time except on Sundays.</p>\\r\\n\"]}"
英文:

I need to display accordion in WKWebView from the html string coming from API response like this.
iOS:如何通过HTML字符串在WkWebView中显示手风琴(Accordion) Swift
I already tried so many solutions in SO to do this but still not able to create it please share some some solution or code to display this as expected.
I am sharing my code

let fullDesc = responseDict?[&quot;description_middle&quot;]?.string ?? &quot;&quot;
                    let htmlString:String! = fullDesc //(postDict?[&quot;description&quot;]!.stringValue ?? &quot;&quot;)
                    
                    //self.detailWeb.customUserAgent = &quot;Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136&quot;

                    
                    self.detailWeb.loadHTMLString(&quot;&lt;html&gt;&lt;body&gt;&lt;style&gt;p{align-items:justify;justify-content:justify} h1, h2, h3, h4, h5, h6{font-size:20px; font-weight:bold;} &lt;/style&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1.0,Proxima Nova-Regular\&quot;&gt;\(htmlString!)&lt;/body&gt;&lt;/html&gt;&quot;, baseURL: nil)

And here is the html string i got from the response

&quot;description_middle&quot;: &quot;{\&quot;ac_title\&quot;:[\&quot;When Should I take this Service?\&quot;,\&quot;What benefits will I get by taking this onsite styling consultation service?\&quot;,\&quot;Can I select a Fashion Stylist of my choice for this consultation?\&quot;,\&quot;What Happens after I make the Payment?\&quot;],\&quot;ac_description\&quot;:[\&quot;&lt;p&gt;You should take this Wardrobe Consultation Service if you are facing any of the following situations:&lt;\\/p&gt;\\r\\n\\r\\n&lt;ul&gt;\\r\\n\\t&lt;li&gt;You are struggling to find clothes that fit and flatter your body type&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;You have a big event coming up and need help putting together the perfect outfit&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;you want to update your professional image and make a great first impression&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;you have a closet full of clothes but nothing to wear&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;you want to build a sustainable wardrobe that is both stylish and environmentally friendly&lt;\\/li&gt;\\r\\n&lt;\\/ul&gt;\\r\\n\&quot;,\&quot;&lt;p&gt;Taking a Wardrobe Consultation Service brings you several benefits. Some of those benefits are given below:&lt;\\/p&gt;\\r\\n\\r\\n&lt;ul&gt;\\r\\n\\t&lt;li&gt;Time and Convenience:&amp;nbsp;A personal stylist saves your time and effort by doing the shopping, research and curating outfits for you, freeing up your own time to focus on other things.&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;Increased Confidence:&amp;nbsp;A stylist can help you develop your personal style, which can lead to increased confidence in your appearance and self-esteem.&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;Expertise:&amp;nbsp;Personal stylists have expertise in fashion, body shapes, color analysis and current trends, allowing you to benefit from their professional knowledge and advice.&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;Maximizing Wardrobe:&amp;nbsp;A stylist can help you to get the most out of your existing wardrobe, by creating new outfits and suggesting key pieces to purchase, making the most of your investment.&lt;\\/li&gt;\\r\\n\\t&lt;li&gt;Cost Savings:&amp;nbsp;By investing in a personal stylist, you may save money in the long run by avoiding costly fashion mistakes, and making informed purchases that add value to your wardrobe.&lt;\\/li&gt;\\r\\n&lt;\\/ul&gt;\\r\\n\&quot;,\&quot;&lt;p&gt;We would be introducing this feature in future. Until then, StyleBuddy will assign you the best available stylist at the time of your booking.&lt;\\/p&gt;\\r\\n\&quot;,\&quot;&lt;p&gt;Our Client Support Team will reach out to you to initiate your service sessions. You will be asked to update a Client Information Form, which is required for the Stylist to prepare for your Service. You can also call or WhatsAPP us on&amp;nbsp;+91-00&amp;nbsp;to enquire about&amp;nbsp;your appointment. This service is available from 10 AM to 7 PM India time except on Sundays.&lt;\\/p&gt;\\r\\n\&quot;]}&quot;

答案1

得分: 1

以下是翻译好的部分代码:

import UIKit
import WebKit

// 将硬编码的响应作为字典
let descriptionMiddle: [String: Any] = [
    "ac_title": [
        "我应该什么时候使用这项服务?",
        "通过参加现场风格咨询服务,我将获得什么好处?",
        "我可以选择自己喜欢的时尚设计师进行咨询吗?",
        "我付款后会发生什么?"
    ],
    "ac_description": [
        "<p>如果您遇到以下任何情况,您应该参加这项衣柜咨询服务:</p><ul><li>您正在努力寻找适合并彰显身材的服装</li><li>您即将有重大活动,需要帮助搭配完美的服装</li><li>您希望更新自己的职业形象,给人留下良好的第一印象</li><li>您的衣柜里挤满了衣服,但却没有合适的着装</li><li>您希望打造既时尚又环保的可持续衣柜</li></ul>",
        "<p>参加衣柜咨询服务会带来多个好处。以下是其中一些好处:</p><ul><li>节省时间和便利性:个人时尚设计师为您购物、研究和策划着装,为您节省时间和精力,使您能够专注于其他事情。</li><li>提高自信心:时尚设计师可以帮助您发展个人风格,从而增强您的外貌和自尊心。</li><li>专业知识:个人时尚设计师在时尚、身体形状、色彩分析和当前趋势方面拥有专业知识,使您能够受益于他们的专业知识和建议。</li><li>最大化衣柜:时尚设计师可以帮助您充分利用现有的衣柜,通过打造新的着装和建议购买关键单品,充分利用您的投资。</li><li>节省成本:通过投资个人时尚设计师,您可能会在长期内节省金钱,避免昂贵的时尚错误,并做出增值您衣柜的明智购买。</li></ul>",
        "<p>我们将在未来引入此功能。在那之前,StyleBuddy将在您预订时为您分配最佳的可用时尚设计师。</p>",
        "<p>我们的客户支持团队将与您联系,开始您的服务会话。您将被要求更新客户信息表格,这是时尚设计师为您的服务做准备所需的。您也可以致电或通过WhatsApp与我们联系,电话:+91-00,咨询您的预约。除了星期天,此服务从印度时间上午10点到下午7点提供。</p>"
    ]
]

class ViewController: UIViewController, WKNavigationDelegate {
    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 创建一个WKWebView实例
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)

        // 加载HTML内容
        loadAccordionHTML()
    }

    private func loadAccordionHTML() {
        let titles = descriptionMiddle["ac_title"] as? [String] ?? []
        let descriptions = descriptionMiddle["ac_description"] as? [String] ?? []

        var accordion = ""
        for i in 1..<titles.count {
            accordion += """
            <details>
              <summary>\(titles[i])</summary>
              <p>\(descriptions[i])</p>
            </details>
            """
        }

        // 根据需要更新/美化HTML内容。
        let htmlString = "<div> \(accordion) </div>"
        webView.loadHTMLString(htmlString, baseURL: nil)
    }
}

附加参考资料:


<details>
<summary>英文:</summary>
As per my understanding you have parsed the response and want to show the response in the form of an Accordion. This can be easily done with `&lt;details&gt;` and `&lt;summary&gt;` tags.
Here is a code for reference:
```swift
import UIKit
import WebKit
// Hardcoded response as a dictionary
let descriptionMiddle: [String: Any] = [
&quot;ac_title&quot;: [
&quot;When Should I take this Service?&quot;,
&quot;What benefits will I get by taking this onsite styling consultation service?&quot;,
&quot;Can I select a Fashion Stylist of my choice for this consultation?&quot;,
&quot;What Happens after I make the Payment?&quot;
],
&quot;ac_description&quot;: [
&quot;&lt;p&gt;You should take this Wardrobe Consultation Service if you are facing any of the following situations:&lt;/p&gt;\r\n\r\n&lt;ul&gt;\r\n\t&lt;li&gt;You are struggling to find clothes that fit and flatter your body type&lt;/li&gt;\r\n\t&lt;li&gt;You have a big event coming up and need help putting together the perfect outfit&lt;/li&gt;\r\n\t&lt;li&gt;you want to update your professional image and make a great first impression&lt;/li&gt;\r\n\t&lt;li&gt;you have a closet full of clothes but nothing to wear&lt;/li&gt;\r\n\t&lt;li&gt;you want to build a sustainable wardrobe that is both stylish and environmentally friendly&lt;/li&gt;\r\n&lt;/ul&gt;\r\n&quot;,
&quot;&lt;p&gt;Taking a Wardrobe Consultation Service brings you several benefits. Some of those benefits are given below:&lt;/p&gt;\r\n\r\n&lt;ul&gt;\r\n\t&lt;li&gt;Time and Convenience:&amp;nbsp;A personal stylist saves your time and effort by doing the shopping, research and curating outfits for you, freeing up your own time to focus on other things.&lt;/li&gt;\r\n\t&lt;li&gt;Increased Confidence:&amp;nbsp;A stylist can help you develop your personal style, which can lead to increased confidence in your appearance and self-esteem.&lt;/li&gt;\r\n\t&lt;li&gt;Expertise:&amp;nbsp;Personal stylists have expertise in fashion, body shapes, color analysis and current trends, allowing you to benefit from their professional knowledge and advice.&lt;/li&gt;\r\n\t&lt;li&gt;Maximizing Wardrobe:&amp;nbsp;A stylist can help you to get the most out of your existing wardrobe, by creating new outfits and suggesting key pieces to purchase, making the most of your investment.&lt;/li&gt;\r\n\t&lt;li&gt;Cost Savings:&amp;nbsp;By investing in a personal stylist, you may save money in the long run by avoiding costly fashion mistakes, and making informed purchases that add value to your wardrobe.&lt;/li&gt;\r\n&lt;/ul&gt;\r\n&quot;,
&quot;&lt;p&gt;We would be introducing this feature in the future. Until then, StyleBuddy will assign you the best available stylist at the time of your booking.&lt;/p&gt;\r\n&quot;,
&quot;&lt;p&gt;Our Client Support Team will reach out to you to initiate your service sessions. You will be asked to update a Client Information Form, which is required for the Stylist to prepare for your Service. You can also call or WhatsApp us on&amp;nbsp;+91-00&amp;nbsp;to inquire about&amp;nbsp;your appointment. This service is available from 10 AM to 7 PM India time except on Sundays.&lt;/p&gt;\r\n&quot;
]
]
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Create a WKWebView instance
webView = WKWebView(frame: view.bounds)
webView.navigationDelegate = self
view.addSubview(webView)
// Load the HTML content
loadAccordionHTML()
}
private func loadAccordionHTML() {
let titles = descriptionMiddle[&quot;ac_title&quot;] as? [String] ?? []
let descriptions = descriptionMiddle[&quot;ac_description&quot;] as? [String] ?? []
var accordion = &quot;&quot;
for i in 1..&lt;titles.count {
accordion += &quot;&quot;&quot;
&lt;details&gt;
&lt;summary&gt;\(titles[i])&lt;/summary&gt;
&lt;p&gt;\(descriptions[i])&lt;/p&gt;
&lt;/details&gt;
&quot;&quot;&quot;
}
// Please update / stylize the html content as needed.
let htmlString = &quot;&lt;div&gt; \(accordion) &lt;/div&gt;&quot;
webView.loadHTMLString(htmlString, baseURL: nil)
}
}

Additional references:

huangapple
  • 本文由 发表于 2023年5月17日 19:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定