ios UITabBarItem标签中有多行

wgeznvg7  于 2022-11-19  发布在  iOS
关注(0)|答案(5)|浏览(144)

我尝试了很多方法,但无法找到一种方法来放置带有lineNumber customised.0的UITabBarItem的标签(我希望将标题放在2行上)。
有办法吗?

e4yzc0pl

e4yzc0pl1#

现在它包含了两个子视图。在0处是imageView,在1处是label。现在把imageview的高度调小一点,这样你就可以把label的高度调大一点,以便有多行。通过代码把label的属性ofnumberoflines设置为0。

let viewTabBar = tabBarItem.value(forKey: "view") as? UIView
let imageView = viewTabBar?.subviews[0] as? UIImageView
let label = viewTabBar?.subviews[1] as? UILabel

现在来玩这个标签。

hi3rlvi2

hi3rlvi22#

更稳定的解决方案:

guard let view = tabBarItem?.value(forKey: "view") as? UIView,
        let label = (view.subviews.flatMap{ $0 as? UILabel }).first,
        let imageView = (view.subviews.flatMap{ $0 as? UIImageView }).first else { return }
7ivaypg9

7ivaypg93#

这是我解决方案
我们需要在viewwillLayoutSubviews内部实现此功能。以更新用户界面并使其正常工作
在这个例子中,在去定制我的第三个标签栏项目只

override func viewWillLayoutSubviews() {
    // acess to list of tab bar items
    if let items = self.tabBar.items {
        // in each item we have a view where we find 2 subviews imageview and label
        // in this example i would like to change
        // access to item view
        let viewTabBar = items[2].value(forKey: "view") as? UIView
        // access to item subviews : imageview and label
        if viewTabBar.subviews.count == 2 {
            let label = viewTabBar?.subviews[1]as? UILabel
            // here is the customization for my label 2 lines
            label?.numberOfLines = 2
            label?.textAlignment = .center
            label!.text = "tab_point".localized
            // here customisation for image insets top and bottom
            items[2].imageInsets = UIEdgeInsets(top: 8, left: 0, bottom: -5, right: 0)
        }
    }
}

这是结果

kxxlusnw

kxxlusnw4#

您不能对UIBarButtonItem执行此操作,因为它不具有与UINavigationItem类似titleView属性!
您只能将字符串设置为标题和选项卡图像!就是这样!
如果您可以选择将标签设置为选项卡项的标题视图,那么您可以将标签的数字设置为0,但在这里您只能设置字符串!

jgzswidk

jgzswidk5#

tabBar.items?.forEach {
        $0.imageInsets = UIEdgeInsets(top: 8, left: 0, bottom: -15, right: 0)
        
        guard let view = $0.value(forKey: "view") as? UIView,
              let label = (view.subviews.compactMap{ $0 as? UILabel }).first,
              let imageView = (view.subviews.compactMap{ $0 as? UIImageView }).first else { return }
        
        label.numberOfLines = 2
        if CBServerManagerApi.sharedManager().currentUser.type == "Local" {
            label.text = titles[element]
        }
        label.lineBreakMode = .byTruncatingTail
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false  
        NSLayoutConstraint.activate([
        label.heightAnchor.constraint(equalToConstant: 30)
        ])
    }

相关问题