Creating an image overlay within HTML text in NSAttributedString with CSS: A step-by-step guide

I am currently working on extracting HTML text that includes a YouTube video. In order to showcase this video, I have implemented a preview image.

The original text is as follows:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n<p><iframe loading=\"lazy\" title=\"Forza Horizon 5 : RTX 4090 24GB ( 8K Maximum Settings RTX ON / DLSS ON )\" width=\"500\" height=\"281\" src=\"https://www.youtube.com/embed/NcHyE_N1QDI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen></iframe></p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

After formatting, it appears like this:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>\n<p><a href='https://www.youtube.com/watch?v=NcHyE_N1QDI'><img src=\"https://img.youtube.com/vi/NcHyE_N1QDI/maxresdefault.jpg\" alt=\"\" width=\"393.0\"/></a></p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

Next, I utilize NSMutableAttributedString and set a new value for the UITextView's attributedText property.

The query pertains to how one can superimpose an image with a play button on top of the preview image to make it evident to users that this is a video. My assumption is that CSS can achieve this, but I am unsure about the correct way to integrate it into the code.

Here is my implementation:

private func formatStringWithYTVideo(text: String, with width: Float) -> String {
        let iframeTexts = matches(for: ".*iframe.*", in: text)
        var newText = text
        
        if !iframeTexts.isEmpty {
            
            for iframeText in iframeTexts {
                let iframeId = matches(for: "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)", in: iframeText);
                
                if !iframeId.isEmpty {
                    let htmlString = """
                    <p><a href='https://www.youtube.com/watch?v=\(iframeId[0])'><img src="https://img.youtube.com/vi/\(iframeId[0])/maxresdefault.jpg" alt="" width="\(width)"/></a></p>
                    """
                    
                    newText = newText.replacingOccurrences(of: iframeText, with: htmlString)
                }
            }
        }
        
        return newText
    }

Answer №1

It seems that achieving this goal through UITextView and CSS is not feasible due to the lack of support for necessary attributes. Fortunately, there are a couple of alternative solutions available.

1: Consider utilizing WKWebView in place of UITextView.

2: Another option is to utilize the

enumerateAttributes(in:options:using:)
method to retrieve a list of attributes, locate the specific image you want to replace, and make the desired changes. You can even create an overlaid image using UIImageView and then convert it into an UIImage with the help of UIGraphicsImageRenderer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

failure in data transmission causing upload issues

Is there a way for me to prevent the character > from causing issues? I have a combo box with an option listed below. I attempted to replace > with &gt;, but it still isn't uploading correctly. <select name="Category3" id="Category3"> ...

Apply CSS styles to the checkbox

I am new to CSS and I need help styling a checkbox element. When the user selects one of the checkboxes, I want the background color to change to yellow. Thank you for any assistance you can provide! .radio_toggle { float:left; } .radio_toggle label ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

What could be causing the Lock Screen audio controls to vanish once I pause the AVAudioPlayer?

I have implemented the use of an instance of AVAudioPlayer to play an audio file in my application. The setup includes playing audio in the background and ensuring the appropriate audio session is configured. Additionally, I am successfully receiving remot ...

Presentation: Troubleshooting Ineffective CSS3 Transitions

I have created a basic slideshow that can accommodate multiple images. Clicking on an image should move to the next slide, and once the last image is clicked, it should loop back to the first slide. The functionality of transitioning between slides seems ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...

What is the best way to activate a function to control animation transitions?

My goal is to manually control transitions in my HTML using JavaScript code, such as a tween library like TweenMax. Instead of relying on CSS for transitions with classes like .ng-enter, I want to target a JavaScript function: function onEnter() { /* tra ...

What is the best way to utilize webpack for transferring files to the distribution directory?

I am trying to figure out how to get webpack to automatically grab the necessary JS and CSS files and place them in the dist folder of my index.html without needing to require or import them. Any suggestions on how to accomplish this task efficiently? ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Display Email content within a bootstrap modal using CSS styling

Is there a way to prevent CSS from overwriting tags on my original page when loading an email body into a modal via ajax call? The email body has its own CSS styles that are affecting the layout of my current page. I've considered renaming all the tag ...

The page background appears to be incomplete in its coloring

As I work on creating a web application for personal use, my goal is to ensure it is mobile-friendly. However, I've encountered an issue where the background of my language page isn't displaying in full blue color as intended. Despite trying diff ...

Include a scroll bar for menu items that contain submenus, while ensuring that the submenu items remain visible

Looking for a way to add a scrollbar to the courses menu list due to its excessive length (refer to the image below). The fixed top navbar prevents scrolling, making it necessary to implement a scrollbar within the menu itself. After applying the followin ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

Choosing options from two separate dropdown menus with the same CSS class name using JavaScript or jQuery: A guide

I am looking to update the values of two dropdowns using the same CSS properties, similar to the design shown in the attached image. Here is the HTML code snippet for reference: <div class="container-fluid" role="main" style="margin-top: 100px;"> ...

Changing textarea html content to an iframe in real time with the use of jQuery

Is it possible to use jQuery to transfer HTML content entered into a textarea to an iframe in real time, without refreshing the page? I have searched for a solution but have not found a clear direction. Any code snippet and explanation would be greatly ap ...

Is it possible to use velocity js to add a gradient color effect to text content?

Can I use velocity js to apply gradient color to text? I've looked at https://css-tricks.com/snippets/css/gradient-text/ My specific need is to dynamically add a changing gradient using js. Thank you in advance. ...

Discovering the power of VBA in combination with Selenium to pinpoint and interact with a particular cell within a table

I am attempting to access a specific cell within a table on a webpage. The cell I need to reach has an id of "flowTile_6". It is highlighted below. I have tried multiple methods, but all resulted in errors. One approach I attempted was using the followi ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Add HTML and JavaScript code dynamically with JavaScript

Currently, I am working on a project that involves an HTML table with some basic JS interactions triggered by user clicks. The structure looks something like this: htmlfile.html ... ... position action ...