Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

ios - Is there a way to set something like adjustsfontsizetofitwidth on UITabBarItem

Trying to get my app accessible for all users and I stumbled upon an issue when creating the items for the TabBar and would love to have a way of fixing it.

I got something like this in my project:

func setupTabBarItems(tabName: String, tabImage: UIImage?, tabSelectedImage: UIImage?) {
    let tabBarItem = UITabBarItem(title: tabName, image: tabImage, selectedImage: tabSelectedImage)

    tabBarItem.title = tabName
    tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: AppColor.primary], for: .selected)
    tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: AppColor.darkDeep], for: .normal)
    tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: AppFont.medium(12)], for: .normal)

    tabBarItem.imageInsets = UIEdgeInsets.init(top: -10, left: 0, bottom: 0, right: 0)
    tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -18)

    DispatchQueue.main.async {
        self.navigationController.tabBarItem = tabBarItem
    }
}

and:

static func medium(_ fontSize: CGFloat) -> UIFont {
    let font = UIFont(name: AppFont.someRandomTextFont, size: fontSize)!
    let fontMetrics = UIFontMetrics(forTextStyle: .body)
    return fontMetrics.scaledFont(for: font)
}

When increasing the dynamic text type, the title gets out of the actual item. For example, when doing this for a UILabel I just check the "Automatically Adjust Font" option and update "Minimum Font Scale" to 0.25.

Is there any way to do something like this in the code describing the TabBarItem programmatically?

Thank you so much!

question from:https://stackoverflow.com/questions/65917025/is-there-a-way-to-set-something-like-adjustsfontsizetofitwidth-on-uitabbaritem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UITabBarItem doesn't contain label - so that you will be able to set minimum scale directly.

Suggestion would be to go with custom views instead of UITabBarItems.

Or if you prefer to continue with UITabBarItem, I suggest that you do measuring by yourself. Measure the size of the text/font you want and if it's too big, make the font size small enough that it will fit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...