Swift将带有子视图的UIView添加到titleView

时间:2018-04-12 11:27:25

标签: ios swift uiview subview titleview

我想自定义导航栏并将带有两个子视图的UIView插入导航栏的标题视图中。 不幸的是,子视图没有显示出来。 你知道为什么吗?

    let titleContainer = UIView()
    titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)

    let searchIcon = UIButton()
    searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
    searchIcon.layer.frame = CGRect(x: 0, y: (UIScreen.main.bounds.size.height - 28) / 2, width: 28, height: 28)
    titleContainer.addSubview(searchIcon)

    let titleLabel = UILabel()
    titleLabel.frame = CGRect(x: 28, y: UIScreen.main.bounds.size.height, width: UIScreen.main.bounds.size.width-28, height: UIScreen.main.bounds.size.height)
    titleLabel.textColor = UIColor(red:255, green:255, blue:255, alpha:1.0)
    titleContainer.addSubview(self.titleLabel)

    self.navigationItem.titleView = titleContainer

问题和预期的解决方案:

enter image description here

2 个答案:

答案 0 :(得分:0)

您是否考虑过以编程方式制作let bar = UINavigationBar(),然后将其添加到:self.view.addSubview(bar)

所以你可以推动所有" UIBarItems"你想要..?

答案 1 :(得分:0)

为什么您使用height所有元素的UIScreen.main.bounds.size.height?请尝试以下代码。

P.S。我已经更改了searchIcon的颜色,因为我没有图像并更改了标签文本的颜色并添加了一些文本以便它可见。

    let titleContainer = UIView()
    titleContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 45)

    let searchIcon = UIButton()
    //searchIcon.setImage(UIImage(named: "search_icon"), for: UIControlState.normal)
    searchIcon.backgroundColor = UIColor.red
    searchIcon.layer.frame = CGRect(x: 0, y: 8, width: 28, height: 28)
    titleContainer.addSubview(searchIcon)

    let titleLabel = UILabel()
    titleLabel.frame = CGRect(x: 28, y: 8, width: UIScreen.main.bounds.size.width-28, height: 30)
    titleLabel.textColor = UIColor.blue//(red:255, green:255, blue:255, alpha:1.0)
    titleContainer.addSubview(titleLabel)
    titleLabel.text = "Sample Text"

    self.navigationItem.titleView = titleContainer

以下是上述代码的屏幕截图:

enter image description here

请根据您的要求相应更改x,y。