【发布时间】:2021-09-27 22:52:49
【问题描述】:
我正在尝试使用 MusicBrainz API 创建一个搜索应用程序,该 API 将返回与用户输入的搜索词匹配的 JSON 数据。
这是我目前的 UI:
import UIKit
import WebKit
class ArtistListViewController: UIViewController{
let tableView = UITableView()
var safeArea: UILayoutGuide!
var artists: [Artists]?
let textField = UITextField()
var searchTerm = "Search"
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
safeArea = view.layoutMarginsGuide
searchBar()
setUpTable()
setUpNavigation()
}
func searchBar(){
view.addSubview(textField)
textField.placeholder = "Search"
textField.frame = CGRect(x: 10,y: 200,width: 300.0,height: 30.0)
textField.borderStyle = UITextField.BorderStyle.line
textField.translatesAutoresizingMaskIntoConstraints = false
//Layout Configs
textField.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
textField.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
textField.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
textField.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setUpTable(){
view.addSubview(tableView)
ArtistSearchModelData().loadArtists(searchTerm: "Adele"){ [weak self] (artists) in
self?.artists = artists
DispatchQueue.main.async{
self?.tableView.reloadData()
}
}
//populate with data
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell")
//turn off autoresizing
tableView.translatesAutoresizingMaskIntoConstraints = false
//Layout Configs
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setUpNavigation(){
self.navigationItem.title = "Artists"
self.navigationController?.navigationBar.barTintColor = .white
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.orange,
NSAttributedString.Key.font: UIFont(name: "Arial-BoldMT", size: 30)
]
}
}
这是我的用户界面的样子:
如您所见,我的搜索栏完全不见了,我不知道如何呈现它。
我尝试使用 UIStackView 但得到了相同的结果。
我尝试在互联网上搜索并找到类似的解决方案,但无法让它们中的任何一个起作用。
将 textField 和 tableView 添加到自定义子视图也不会呈现任何内容,可能是因为它们是函数?我是不是走错路了?
感谢任何帮助!
【问题讨论】:
-
您首先向视图添加一个文本字段。然后向视图中添加一个表视图。那么你期待什么?你用 insertSubview(_, at: ) 改变出现的顺序吗?
标签: ios swift uitableview uikit uitextfield