Search code examples
listurlswiftuiclickable

How to create a list in Content View with clickable URLs in SwiftUI?


This is a question that I couldn't find an answer for but I figured it out with friend's help eventually (there is right answer given by me lower in this thread).

I wanted to create a list based in JSON I downloaded from the GitHub website, but I couldn't find how to make the list items clickable, so that they would allow the user to see the repositories they were searching for.

Please note that this question is regarding SwiftUI, not Storyboards approach to iOS programming!


Solution

  • The answer was to use the WebView. The main code:

    import SwiftUI
    
    struct ContentView: View {
        @StateObject private var viewModel = ContentViewModel()
        
        var body: some View {
    
    HStack {
                        TextField("Enter search", text: $viewModel.query)
                        Button("Search") {
                            viewModel.fetchRepos()
                        }
                    }
                    List(viewModel.searchResults, id: \.id) { item in
                        VStack(alignment: .leading) {
    /* the lines answering to the query start from the Link command and follow until the end */ 
                            Link(destination: URL(string: item.htmlUrl)!, label: {
                                Text(item.fullName)
                                    .font(.headline)
                                    .foregroundColor(.blue)
                            })
                        }
                    }
    }
    

    I commented where the answer starts. And for a better understanding of the code, these are the API keys:

    import SwiftUI
    
    struct Root: Codable {
        let items: [Item]
    
        enum CodingKeys: String, CodingKey {
            case items
        }
    }
    
    struct Item: Identifiable, Codable {
        let id: Int
        let htmlUrl: String
        let fullName: String
    
        enum CodingKeys: String, CodingKey {
            case id
            case htmlUrl = "html_url"
            case fullName = "full_name"
        }
    }
    

    Have fun creating your clickable lists that will let your users go to the corresponding URLs :)

    P.S. In this answer the URLSession, JSONDecoder and query handling parts are missing but they would complicate it and are not crucial to this problem. You can research them on Stack Overflow in different topics :)