两行提示 - Swift

问题描述 投票:0回答:3

有没有办法为快捷导航栏制作两行提示?我目前找不到要修改的属性。我当前在提示中显示的文本来自外部数据模型,因此有时文本数量超出了屏幕显示的范围。谢谢。

Image Showing Text Outside of Frame

ios swift uinavigationbar
3个回答
0
投票

你可以这样尝试:

斯威夫特3.0

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:50)) //width is subject to change, Defined as per your screen
label.backgroundColor =.clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor.white
label.text = "Your Text here"
self.navigationItem.titleView = label

0
投票

导航栏有标题和提示

navigationItem.title = "Title, large"
navigationItem.prompt = "One line prompt, small text, auto-shrink"  

有一个提示可能比有一个自定义标题视图更好,因为它给你更多的高度,并且它与搜索栏配合得很好。但请确保这确实是您想要的,因为下面的代码并未在所有设备 iOS 版本上进行测试。这只会让您了解如何控制导航栏中几乎所有有关布局的内容

class MyNavigationBar: UINavigationBar {
func allSubViews(views: [UIView]) {
    for view in views {
        if let label = view as? UILabel, label.adjustsFontSizeToFitWidth {
            if label.numberOfLines != 2 { //this is the promp label
                label.numberOfLines = 2
                let parent = label.superview
                parent?.frame = CGRect(x: 0, y: 0, width: parent!.bounds.width, height: 44)

                parent!.removeConstraints(parent!.constraints)
                label.removeConstraints(label.constraints)
                label.leadingAnchor.constraint(equalTo: parent!.leadingAnchor, constant: 20).isActive = true
                label.trailingAnchor.constraint(equalTo: parent!.trailingAnchor, constant: -20).isActive = true
                label.topAnchor.constraint(equalTo: parent!.topAnchor).isActive = true
                label.bottomAnchor.constraint(equalTo: parent!.bottomAnchor).isActive = true
            }
            return
        }
        
        self.allSubViews(views: view.subviews)
    }
}

override func layoutSubviews() {
    super.layoutSubviews()
    allSubViews(views: self.subviews)
}
}

要使用导航栏,请使用:

let navVc = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: nil)

0
投票

您可以将提示配置为多行,如下图所示。诀窍是搜索 UINavigationBar 的所有子视图并以某种方式找到提示视图。执行此操作的一种方法是首先使用一些众所周知的文本加载提示,然后在子视图中搜索该众所周知的文本。在我的示例代码中,我在搜索之前将“默认提示”存储在 navigationItem.prompt 中。

   func findPromptView( view: UIView )
   {
        for item in view.subviews {
            if let label = item as? UILabel {
                if let text = label.text {
                    print(text)
                    if (text == "Default Prompt") {
                        label.numberOfLines = 2
                        label.textAlignment = .center
                    }
                }
            }
            if item.subviews.count > 0 {
                findPromptView( view: item )
            }
        }
    }

    if let navBar = navigationController?.navigationBar {
        navigationItem.prompt = "Default Prompt"
        findPromptView( view: navBar)
    }

© www.soinside.com 2019 - 2024. All rights reserved.