我是swift开发的新手。我删除了主故事板,因为我想尝试以编程方式开发所有内容。我想添加带有标题的导航栏。有什么建议吗:
class ViewController: UIViewController {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .white
return imageView
}()
private let button: UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.setTitle("Random Photo", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
let colors: [UIColor] = [
.systemRed,
.systemBlue,
.systemCyan,
.systemGray,
.systemIndigo
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .systemRed
view.addSubview(imageView)
imageView.frame = CGRect(
x: 0,
y:0,
width: 300,
height: 300
)
imageView.center = view.center
view.addSubview(button)
getRandomPhoto()
button.addTarget(self, action: #selector(didTapButton), for: UIControl.Event.touchUpInside)
}
@objc func didTapButton(){
getRandomPhoto()
view.backgroundColor = colors.randomElement()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
button.frame = CGRect(
x:30,
y:view.frame.size.height-150-view.safeAreaInsets.bottom,
width: view.frame.size.width-60,
height: 55
)
}
func getRandomPhoto(){
let urlString = "https://source.unsplash.com/random/600x600"
let url = URL(string: urlString)!
guard let data = try? Data(contentsOf: url) else {
return
}
imageView.image = UIImage(data: data)
}
}
- 我已经试过了,但是它没有显示任何标题。任何帮助显示导航标题栏。
1条答案
按热度按时间ghhaqwfi1#
要以编程方式设置导航标题栏:
请使用上面的代码段以编程方式设置导航标题栏。