Easily show RichText(html) in SwiftUI

Overview

RichText

스크린샷 2021-07-25 오후 3 22 03 스크린샷 2021-07-25 오후 3 22 11
LightMode DarkMode

Code

import SwiftUI
import RichText

struct RichText_Test: View {
    @State var  html = ""
    
    var body: some View {
       ScrollView{
            RichText(html: html, lineHeight: 170, imageRadius: 0, fontType: .default, colorScheme: .automatic, colorImportant: false)
                .placeholder {
                    Text("loading")
                }
        }
    }
}

struct RichText_Test_Previews: PreviewProvider {
    static var previews: some View {
        RichText_Test()
    }
}

Sample Text

Sample
Non quam nostram quidem, inquit Pomponius iocans;

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quis istum dolorem timet? Sit sane ista voluptas. Quis est tam dissimile homini. Duo Reges: constructio interrete. Quam illa ardentis amores excitaret sui! Cur tandem?

Avaritiamne minuis?
Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?
Immo videri fortasse.
Quae qui non vident, nihil umquam magnum ac cognitione dignum amaverunt.
Si longus, levis.
Ita ne hoc quidem modo paria peccata sunt.
  1. Possumusne ergo in vita summum bonum dicere, cum id ne in cena quidem posse videamur?
  2. Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?
  3. Unum nescio, quo modo possit, si luxuriosus sit, finitas cupiditates habere.
Aristoteles, Xenocrates, tota illa familia non dabit, quippe qui valitudinem, vires, divitias, gloriam, multa alia bona esse dicant, laudabilia non dicant.

Scrupulum, inquam, abeunti; Conferam tecum, quam cuique verso rem subicias; Audeo dicere, inquit. Maximus dolor, inquit, brevis est. Nos commodius agimus.

  • Cur igitur, inquam, res tam dissimiles eodem nomine appellas?
  • Omnia peccata paria dicitis.

Laboro autem non sine causa;

Itaque contra est, ac dicitis; Illa argumenta propria videamus, cur omnia sint paria peccata.

Nunc dicam de voluptate, nihil scilicet novi, ea tamen, quae
        te ipsum probaturum esse confidam.

        Sin est etiam corpus, ista explanatio naturae nempe hoc
        effecerit, ut ea, quae ante explanationem tenebamus,
        relinquamus.
        
""" var body: some View { ScrollView{ RichText(html: html, lineHeight: 170, imageRadius: 16, fontType: .default, colorScheme: .automatic, colorImportant: false) .placeholder { Text("loading") } .disabled(true)// if you don't want interaction .padding(.horizontal, 16) } // .background( // Color.black.ignoresSafeArea() // ) } } struct RichText_Test_Previews: PreviewProvider { static var previews: some View { RichText_Test() } } ">
import SwiftUI
import RichText

struct RichText_Test: View {
    @State var  html = """
        

Non quam nostram quidem, inquit Pomponius iocans;

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quis istum dolorem timet? Sit sane ista voluptas. Quis est tam dissimile homini. Duo Reges: constructio interrete. Quam illa ardentis amores excitaret sui! Cur tandem?

Avaritiamne minuis?
Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?
Immo videri fortasse.
Quae qui non vident, nihil umquam magnum ac cognitione dignum amaverunt.
Si longus, levis.
Ita ne hoc quidem modo paria peccata sunt.
  1. Possumusne ergo in vita summum bonum dicere, cum id ne in cena quidem posse videamur?
  2. Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?
  3. Unum nescio, quo modo possit, si luxuriosus sit, finitas cupiditates habere.
Aristoteles, Xenocrates, tota illa familia non dabit, quippe qui valitudinem, vires, divitias, gloriam, multa alia bona esse dicant, laudabilia non dicant.

Scrupulum, inquam, abeunti; Conferam tecum, quam cuique verso rem subicias; Audeo dicere, inquit. Maximus dolor, inquit, brevis est. Nos commodius agimus.

  • Cur igitur, inquam, res tam dissimiles eodem nomine appellas?
  • Omnia peccata paria dicitis.

Laboro autem non sine causa;

Itaque contra est, ac dicitis; Illa argumenta propria videamus, cur omnia sint paria peccata.

Nunc dicam de voluptate, nihil scilicet novi, ea tamen, quae
        te ipsum probaturum esse confidam.

        Sin est etiam corpus, ista explanatio naturae nempe hoc
        effecerit, ut ea, quae ante explanationem tenebamus,
        relinquamus.
        
""" var body: some View { ScrollView{ RichText(html: html, lineHeight: 170, imageRadius: 16, fontType: .default, colorScheme: .automatic, colorImportant: false) .placeholder { Text("loading") } .disabled(true)// if you don't want interaction .padding(.horizontal, 16) } // .background( // Color.black.ignoresSafeArea() // ) } } struct RichText_Test_Previews: PreviewProvider { static var previews: some View { RichText_Test() } }

How To Use

Variable explanation

  • html : which you want to show (String type)

Optional

  • lineHeight (optional, default: 170) : Height of each line
  • imageRadius (optional, default: 0) : Radius of image corner
  • fontType(optional, default : default): Font type in html view but not yet working properly
  • colorScheme(optional, default : automatic) : light or dark mode (it changes text color)
  • colorImportant (optional, default: false) : css '!important', It ignores the color in variable 'html' when colorImportant is true.
  • placeholder(optional,default: EmptyView()) : What to display until Richtext views are completely drawn (View type)

Planned (Future work):

moreOption

Comments
  • CSS Support, Improvements

    CSS Support, Improvements

    • Added custom CSS support.
    • Added configuration and isAnimated parameters to .SFSafariView case, which provides customizations like Reader Mode.
    • Removed .SFSafariViewWithReader, because it can be already done with configuration in .SFSafariView.
    opened by macbookator 5
  • Question about using custom fonts

    Question about using custom fonts

    I'm trying to get a custom font rendering in my webview. I feel like I'm doing all the right steps but I'm unable to see a font change. I tried using the FontType.custom with a name and a UIFont. The UIFont was definitely not nil and was the correct font I wanted passed in. Should using this modifier be the only thing I need? I also tried using custom CSS to change the font. Nothing worked though. Does someone have an example using a custom font just so I could compare. For more project context I added this library as a local package because of needing a few small changes to styling. The custom fonts are added to the main target of the project. Do they need to be added as resources to local package?

    Thanks for the library - it's very nice

    bug 
    opened by jfclifton 4
  • Handling combine/state changes?

    Handling combine/state changes?

    Hello and thank you for sharing this! It appears to be working really well for the initial render, but from your example in the readme, changes to the @State var html won't be reflected by the webview. It seems like this function updateUIView would need to get implemented yea? I took a quick pass at this, so lmk if this seems reasonable and ill make a PR:

    public func updateUIView(_ uiView: WKWebView, context: Context) {
            let htmlStart = """
                <HTML>
                <head>
                    <meta name='viewport' content='width=device-width, shrink-to-fit=YES, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>
                </head>
                """
            let htmlEnd = "</BODY></HTML>"
            let htmlString = "\(htmlStart)\(css(colorScheme: self.colorScheme))\(html)\(htmlEnd)"
            uiView.loadHTMLString(htmlString, baseURL:  nil)
        }
    

    I guess we might want to factor that bit out of makeUIView and updateUIView

    opened by wrunk 3
  • Normal text doesn't show up

    Normal text doesn't show up

    Hi, I have the following text:

    USDC is a fully collateralized US dollar stablecoin. USDC is the bridge between dollars and trading on cryptocurrency exchanges. The technology behind CENTRE makes it possible to exchange value between people, businesses and financial institutions just like email between mail services and texts between SMS providers. We believe by removing artificial economic borders, we can create a more inclusive global economy.

    and it's not showing up:

    image

    opened by afern247 2
  • Using linkColor change the links color to the default WebView blue <a> color

    Using linkColor change the links color to the default WebView blue color

    If I don't set the .linkColor, the link color uses the RichText default light blue color. But when I try to set my custom color, it does not change to the desired color and fallbacks to the dark blue link color.

    RichText(html: htmlString)
            .linkColor(light: Color.white, dark: Color.white)
    

    I am not sure if is related but I am testing this on the latest Xcode 14 beta 5.

    opened by axiel7 1
  • Text does not show in dark mode

    Text does not show in dark mode

    RichText works fine in light mode - but I don't see anything in dark mode. Just a blank black screen.

    RichText(html: myHtml)
        .placeholder {
            Text("Loading myHtml")
        }
    
    opened by murasu 1
  • New Features, Performance Improvements, Bug Fixes

    New Features, Performance Improvements, Bug Fixes

    New Functions:

    • customCSS(_:) allows developer to add custom CSS to WebView.
    • foregroundColor(light:dark:) allows developer to replace text color with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • linkColor(light:dark:) allows developer to replace link colors inside HTML with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • Replaced colorImportant(_:) with colorPreference(forceColor:).
    • SwiftUI's multilineTextAlignment(_:) also works with RichText.

    Model Changes:

    • View preferences such as font color, now storing at Configuration struct.
    • Some models renamed for compatible to Swift API Design Guidelines.
    • ColorSet now includes important option.
    • FontType enum now supports custom fonts.

    Bug Fixes:

    • Storing WKWebView inside class is caused to console warnings and lots of performance issues. And this may cause slowdowns and freezes. Now, WKWebView is not storing inside class, it is declared inside makeUIView(context:) function.
    • Plain text inputs causes to styles not work properly. This bug is fixed by adding input inside
      element.
    opened by macbookator 1
  • SFSafariViewController Reader Mode Support

    SFSafariViewController Reader Mode Support

    I added a new case to linkOpenType. When SFSafariViewWithReader case selected, RichText opens links with SFSafariViewController, on Reader mode if available.

    opened by macbookator 1
  • <Figure> Markup Bug

    Markup Bug

    While it renders

    . it is offset from the rest of the text.

    Here is the example HTML text:

    <figure data-align=\"center\" data-size=\"large\" data-img-src=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" data-ref-id=\"1300-4052233\" data-ratio=\"0.33333333333333\" data-width=\"900\" data-embed-type=\"image\" style=\"width: 900px\"><a class=\"fluid-height\" style=\"padding-bottom:33.3%\" href=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" data-ref-id=\"1300-4052233\"><img alt=\"The days of easily modding your Steam to look the way you want are, sadly, over.\" src=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" srcset=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png 900w, https://www.gamespot.com/a/uploads/scale_medium/1596/15969599/4052233-steamskins2.png 480w\" sizes=\"(max-width: 900px) 100vw, 900px\" data-width=\"900\"></a><figcaption>The days of easily modding your Steam to look the way you want are, sadly, over.</figcaption></figure>

    Here is what is rendered in SwiftUI

    CleanShot 2022-10-23 at 14 22 54@2x

    Can you advise if there is anything I can do to resolve this or if it is a known bug?

    opened by solidHeroLink 0
  • <DETAILS>...</DETAILS>

    ...

    I really like this package but I've run into an issue. I've got this code:

    import SwiftUI import RichText struct MainView : View { var body: some View { ScrollView { RichText(html: Documents.Welcome) } } and when it runs I get a bunch of warnings: [ViewportSizing] maximumViewportInset cannot be larger than frame (similarly for minimumViewportInset). Documents.Welcome is quite large but the warnings didn't seem to be a problem.

    But today I added a "details" section:

    CLICK HERE

    There's a lot of text here.

    and nothing renders after the details link. The same document loads in web browsers (Chrome, Safari, etc) perfectly ok. bug 
    opened by CarolSmall 1
  • Does not obey frame

    Does not obey frame

    Screen Shot 2022-07-20 at 5 14 09 PM

    Frame is set to 48 tall.

    Message body: <p>This is a <strong>fancy</strong> <strong><span style=\"color: rgb(226, 80, 65);\">HTML</span></strong> <span style=\"background-color: rgb(97, 189, 109);\">message</span> with some styling.</p><p>And a <a href=\"http://www.google.com\" target=\"_blank\">link to google</a>.</p>

    opened by Captnwalker1 2
  • Horizontal Scroll

    Horizontal Scroll

    Hi, im using the pod, but i have problems when i want to use horizontal scroll and overflows not work when create the css style.

    i already support this?

    opened by flexingCode 0
Releases(2.1.1)
  • 2.1.1(Oct 6, 2022)

  • 2.1.0(Sep 11, 2022)

    ✨ New Functions:

    • Handle mailto: and tel:
    • Make configuration public

    📝 Update README

    • Modified to match the changed code
    • Add modifier description

    Contributors

    Thanks to @ChaosCoder #20

    Source code(tar.gz)
    Source code(zip)
  • 2.0.1(Aug 10, 2022)

  • 2.0.0(Aug 6, 2022)

    ✨ New Functions:

    • customCSS(_:) allows developer to add custom CSS to WebView.
    • foregroundColor(light:dark:) allows developer to replace text color with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • linkColor(light:dark:) allows developer to replace link colors inside HTML with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • Replaced colorImportant(_:) with colorPreference(forceColor:).
    • SwiftUI's multilineTextAlignment(_:) also works with RichText.

    ♻️ Model Changes:

    • View preferences such as font color, now storing at Configuration struct.
    • Some models renamed for compatible to Swift API Design Guidelines.
    • ColorSet now includes important option.
    • FontType enum now supports custom fonts.

    🐛 Bug Fixes:

    • Storing WKWebView inside class is caused to console warnings and lots of performance issues. And this may cause slowdowns and freezes. Now, WKWebView is not storing inside class, it is declared inside makeUIView(context:) function.
    • Plain text inputs causes to styles not work properly. This bug is fixed by adding input inside
      element.

    Contributors

    Thanks to @macbookator #12

    Source code(tar.gz)
    Source code(zip)
  • v2.0-beta(Jun 9, 2022)

    New Functions:

    • customCSS(_:) allows developer to add custom CSS to WebView.
    • foregroundColor(light:dark:) allows developer to replace text color with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • linkColor(light:dark:) allows developer to replace link colors inside HTML with UIColor and SwiftUI's Color. It supports multiple color schemes.
    • Replaced colorImportant(_:) with colorPreference(forceColor:).
    • SwiftUI's multilineTextAlignment(_:) also works with RichText.

    Model Changes:

    • View preferences such as font color, now storing at Configuration struct.
    • Some models renamed for compatible to Swift API Design Guidelines.
    • ColorSet now includes important option.
    • FontType enum now supports custom fonts.

    Bug Fixes:

    • Storing WKWebView inside class is caused to console warnings and lots of performance issues. And this may cause slowdowns and freezes. Now, WKWebView is not storing inside class, it is declared inside makeUIView(context:) function.
    • Plain text inputs causes to styles not work properly. This bug is fixed by adding input inside
      element.

    Contributors

    Thanks to @macbookator #12

    Source code(tar.gz)
    Source code(zip)
  • 1.7.0(Mar 1, 2022)

  • 1.6.0(Jan 5, 2022)

  • 1.5(Aug 27, 2021)

  • 1.2(Jul 25, 2021)

Owner
null
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Pavel Sharanda 1.1k Jan 8, 2023
An Objective-C framework for converting Markdown to HTML.

MMMarkdown MMMarkdown is an Objective-C framework for converting Markdown to HTML. It is compatible with OS X 10.7+, iOS 8.0+, tvOS, and watchOS. Unli

Matt Diephouse 1.2k Dec 14, 2022
Methods to allow using HTML code with CoreText

DTCoreText This project aims to duplicate the methods present on Mac OSX which allow creation of NSAttributedString from HTML code on iOS. The project

Cocoanetics 6.2k Jan 6, 2023
PySwiftyRegex - Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way.

Ce Zheng 232 Oct 12, 2022
Texstyle allows you to format iOS attributed strings easily.

Texstyle allows you to format attributed strings easily. Features Applying attributes with strong typing and autocompletion Cache for attributes Subst

Rosberry 79 Sep 9, 2022
Like a SwiftUI ViewBuilder, but for Text

TextBuilder Introduction Text composition in SwiftUI can often be cumbersome, especially when there's logic affecting its format and content. TextBuil

David Roman 180 Dec 26, 2022
Markdown in SwiftUI, and some other interesting components.

RoomTime RoomTime is a bundle of tools developed in my app RoomTime Lite. ( ?? RoomTime Lite is still in development) Features TextArea AutoWrap Markd

Chen SiWei 56 Dec 20, 2022
A lightning fast, native SwiftUI scratchpad/text editor.

Sedit A lightning fast, native SwiftUI scratchpad/text editor. Sedit (Swift Edit, as in the language and as in fast) is a lightning fast basic text ed

null 5 Jan 28, 2022
SensibleStyling - Helpers for sensible SwiftUI styling

SensibleStyling Helpers for sensible SwiftUI styling. License See the LICENSE fi

apparata 5 Dec 18, 2022
Generate SwiftUI Text or AttributedString from markdown strings with custom style names.

iOS 15.0 / macOS 12.0 / tvOS 15.0 / watchOS 8.0 StyledMarkdown is a mini library that lets you define custom styles in code and use them in your local

null 19 Dec 7, 2022
_Text is a simple augmentation to SwiftUI that makes styling easier

_Text _Text is a simple augmentation to SwiftUI that makes styling easier. By utilizing the environment it is possible to apply text modifiers to any

Eric Lewis 1 Feb 22, 2022
Render Markdown text in SwiftUI, preview based on the Marked implementation

Markdown Render Markdown text in SwiftUI. It is a preview based on the Marked implementation. swiftui-markdown.mov Installation You can add MarkdownUI

小弟调调™ 26 Dec 20, 2022
AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextView depending on the platform.

AttributedText AttributedText is a Swift µpackage that provides NSAttributedString rendering in SwiftUI by wrapping either an NSTextView or a UITextVi

null 1 Jul 18, 2022
Rendering Markdown text natively in SwiftUI.

MarkdownView MarkdownView is a Swift Package for rendering Markdown text natively in SwiftUI. Thanks to apple/swift-markdown, it can fully compliant w

LiYanan2004 13 Oct 22, 2022
A result builder that build HTML parser and transform HTML elements to strongly-typed result, inspired by RegexBuilder.

HTMLParserBuilder A result builder that build HTML parser and transform HTML elements to strongly-typed result, inspired by RegexBuilder. Note: Captur

null 4 Aug 25, 2022
Easily show HUDs with SwiftUI! Lightweight SwiftUI wrapper for JGProgressHUD for iOS, tvOS, Catalyst.

JGProgressHUD-SwiftUI This is a lightweight and easy-to-use SwiftUI wrapper for JGProgressHUD, giving you access to the large and proven feature set o

Jonas Gessner 78 Dec 21, 2022
Mahmoud-Abdelwahab 5 Nov 23, 2022
Show the confetti only when the user is having fun, and if not having fun, don't show it.

SPConfetti - A simple solution to show the confetti to the user. Smoothly starts and stops. Allow set multiply diffrent particles at once. You can chang

Ivan Vorobei 225 Dec 30, 2022
📄 A Swift DSL for writing type-safe HTML/CSS in SwiftUI way

?? swift-web-page (swep) Swep is a Swift DSL for writing type-safe HTML/CSS in SwiftUI way. Table of Contents Motivation Examples Safety Design FAQ In

Abdullah Aljahdali 14 Dec 31, 2022
Easily hide and show a view controller's navigation bar (and tab bar) as a user scrolls

HidingNavigationBar An easy to use library (written in Swift) that manages hiding and showing a navigation bar as a user scrolls. Features Usage Custo

Tristan Himmelman 1k Dec 21, 2022