Multiple lines in UITabBarItem Label

前端 未结 4 1779
说谎
说谎 2021-01-19 12:06

I\'ve tried many things but impossible to find a way to put the label of a UITabBarItem with a lineNumber customised.0 (i would like to get the title on 2 lines).

Is

相关标签:
4条回答
  • 2021-01-19 12:31

    you can not do this with UIBarButtonItem because it doesn't have property titleView like UINavigationItem!

    You can set only string as title and tab image! that's it!

    If you have option to set label as titleview of tabbaritem then you can take label with numberofline 0 but here you can set string only!

    0 讨论(0)
  • 2021-01-19 12:38

    More stable solution:

    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 }
    
    0 讨论(0)
  • 2021-01-19 12:46

    this is my solution for that

    we need to implement this inside viewwillLayoutSubviews. to update the ui and make it works

    in this example in going to customize my 3rd tab bar item only

    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)
            }
        }
    }
    

    and here is the result

    0 讨论(0)
  • 2021-01-19 12:48

    Now it contains two subviews. At 0 it is imageView and at 1 it is label. Now make the height of imageview a bit smaller so that you can give the height of label a bit larger to have multiple lines. Set the property ofnumberoflines of the label to 0 via code.

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

    and now play with this label.

    0 讨论(0)
提交回复
热议问题