首页 > 解决方案 > 以编程方式为我的 NavigationBar 创建了一个标题,但是,没有出现在正确的位置?

问题描述

在此处输入图像描述你好,

如果有人可以帮助我解决以下问题,将不胜感激。

我创建了一个UINavigationBar类,我从中创建了一个实例ViewController,我想在其中实现它。但是,NavigationBar 的标题没有出现在我想要的位置。如图所示,标题当前显示在 NavigationBar 的最顶部(即,在深蓝色区域中)。如何使标题出现在浅蓝色区域?以及如何根据需要修改其在 NavigationBar 区域内的位置?

谢谢,沙迪。

import UIKit
import ChameleonFramework

class CustomNavigationBar: UINavigationBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupNavigationBar()  
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupNavigationBar()
    }

    func setupNavigationBar() {
        isTranslucent = true
        backgroundColor = .blue
        barStyle = .blackTranslucent
        var fsafdsaf = topItem?.title
        fsafdsaf = "dsadfsadfsafsdafsad"
        let titlfsdfe = UINavigationItem.init(title: fsafdsaf!)
        setItems([titlfsdfe], animated: false)
    }

}

标签: iosswiftuinavigationbar

解决方案


好吧,我设法解决了我的问题,但是,非常欢迎任何进一步的替代方案。

基本上,我在 UINavigationBar 类的导航栏中添加了一个 UILabel 并设法解决了这个问题。

解决方法参考以下代码:在此处输入图像描述

import UIKit

import ChameleonFramework

class CustomNavigationBar: UINavigationBar {

    override init(frame: CGRect) {

        super.init(frame: frame)

        setupNavigationBar()

    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        setupNavigationBar()

    }

    func setupNavigationBar() {

        isTranslucent = true

        backgroundColor = .blue

        barStyle = .blackTranslucent

        let navigationBarTitleFrame = CGRect(x: 200, y: 50, width: 120, height: 25)

        let navigationBarTitle = UILabel(frame: navigationBarTitleFrame)

        navigationBarTitle.text = "This is my title"

        navigationBarTitle.textAlignment = .center

        navigationBarTitle.textColor = .white

        navigationBarTitle.layer.borderWidth = 3.0

        self.addSubview(navigationBarTitle)

    }

}

推荐阅读