如何让文本适合 UIButton?

2023-07-07移动开发问题
1

本文介绍了如何让文本适合 UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

按钮大小足够了,但是当我更改标题时,标题文本无法适应按钮宽度.任何SDK功能都可以解决这个问题,还是我需要手动编码才能解决?

Button size is enough, however when I change title, the title text cannot fit the button width. Any SDK function can solve this problem, or I need to manually code to solve it?

请参考以下图片.

在 nib 文件中设计.

design in the nib file.

模拟器中的初始显示

当我更改标题文本时

  1. _button.titleLabel.adjustsFontSizeToFitWidth = YES;
    这种方式会改变我的字体大小.我不能接受这种方式.

  1. _button.titleLabel.adjustsFontSizeToFitWidth = YES;
    the way will change my font size. I cannot accept the way.

[_button setTitleEdgeInsets:UIEdgeInsetsMake(10.0, 10.0, 0.0,0.0)];
方式只改变标签的位置,不改变标签的大小.

[_button setTitleEdgeInsets:UIEdgeInsetsMake(10.0, 10.0, 0.0,0.0)];
the way change label's position only, not label size.

[_button.titleLabel sizeToFit];
结果与图片(3)相同.

[_button.titleLabel sizeToFit];
result is same with picture(3).

[_button sizeToFit];
标题移到左上角,标题还是一样的结果.

[_button sizeToFit];
title moved to upper left corner, and the title still the same result.

一头雾水,我的按钮大小够大,标题怎么这么小?

Just confused, my button size is big enough, why title size is so small?

推荐答案

使用这个.

目标-c

button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping; 

斯威夫特 2.0

button.titleLabel?.numberOfLines = 0
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping

注意:Swift 代码礼貌:@Rachel Harvey

NOTE: Swift code courtesy: @Rachel Harvey

斯威夫特 5.0

button.titleLabel?.numberOfLines = 0
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byWordWrapping

这篇关于如何让文本适合 UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

[ios.cocos2d+box2d]如何禁用自动旋转?
[ios.cocos2d+box2d]how to disable auto-rotation?([ios.cocos2d+box2d]如何禁用自动旋转?)...
2024-08-12 移动开发问题
7

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?
How can I implement a virtual joystick for a cocos2d game outside the cocos2d environment?(如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?)...
2024-08-12 移动开发问题
13