ios 快速导航标题栏

3pmvbmvn  于 2023-02-26  发布在  iOS
关注(0)|答案(1)|浏览(147)

我是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)
    }
}
  • 我已经试过了,但是它没有显示任何标题。任何帮助显示导航标题栏。
ghhaqwfi

ghhaqwfi1#

要以编程方式设置导航标题栏:

override func viewDidLoad() {
   super.viewDidLoad()
   setNavigationTitleBar()
}

func setNavigationTitleBar() {
    let screenSize: CGRect = UIScreen.main.bounds
    let navBar = UINavigationBar(frame: CGRect(x: 0, y: 50, width: screenSize.width, height: 80))
    let navItem = UINavigationItem(title: "Navigation Title Bar")
    navBar.setItems([navItem], animated: false)
    self.view.addSubview(navBar)
}

请使用上面的代码段以编程方式设置导航标题栏。

相关问题