TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.