UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Button inside Text (SwiftUI)

Forums > SwiftUI

I want to insert a button inside the text, something like

 Text("MyLocalizedKey \(Button(action:{}){Text("tap me").foregroundColor(.blue)})")

or To be clearfied ,

I just want to implemnet a away like instagram comments, when the comment contains #swift, the swift word become a button with blue color.

3      

Prior to SwiftUI 3, there's no way to really do that in native SwiftUI; you need to use a (UI|NS)ViewRepresentable to wrap a (UI|NS)TextView and display an NSAttributedString that has the link attribute set for the text you want to be a link.

In iOS 15 and SwiftUI 3, you can use the new AttributedString. You can either manually add links or use Markdown to supply the links:

import SwiftUI

struct ContentView: View {

    var attributedString: AttributedString

    init() {
        //either like this:
        attributedString = AttributedString("Hello, #swift")
        let range = attributedString.range(of: "#swift")!
        attributedString[range].link = URL(string: "https://www.hackingwithswift.com")!

        //or like this:
        attributedString = try! AttributedString(markdown: "Hello, [#swift](https://www.hackingwithswift.com)")
    }

    var body: some View {
        Text(attributedString)
            .padding()
    }
}

5      

thank you @roosterboy, Xcode 13 is not working well on my mac, I appreciate your response. I will try (UI|NS)ViewRepresentable for that.

3      

thanks for the awesome information.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.