這是一個我找不到答案的問題,但我最終在朋友的幫助下想通了(我在這個帖子的下方給出了正確的答案)。
我想創建一個基于從 GitHub 網站下載的 JSON 的串列,但我找不到如何使串列項可點擊,以便它們允許用戶查看他們正在搜索的存盤庫。
請注意,這個問題是關于 SwiftUI,而不是 iOS 編程的 Storyboard 方法!
uj5u.com熱心網友回復:
答案是使用 WebView。主要代碼:
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)
})
}
}
}
我評論了答案從哪里開始。為了更好地理解代碼,這些是 API 密鑰:
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"
}
}
玩得開心創建可點擊串列,讓您的用戶轉到相應的 URL :)
PS 在這個答案中,缺少 URLSession、JSONDecoder 和查詢處理部分,但它們會使它復雜化并且對這個問題并不重要。您可以在不同主題的 Stack Overflow 上研究它們 :)
uj5u.com熱心網友回復:
請使用 UITableView 作為 Clickable ListView。
class MyViewController: UIViewController {
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414838.html
標籤:
上一篇:C#獲取瀏覽器活動標簽的URL
