Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UIButton未使用指定的文本展开_Ios_Swift - Fatal编程技术网

Ios UIButton未使用指定的文本展开

Ios UIButton未使用指定的文本展开,ios,swift,Ios,Swift,我在屏幕上有一个按钮。UIButton上没有宽度限制。我喜欢我的UIButton扩展到指定的文本。但结果是: 以下是实施方案: self.translatedPhraseButton.setTitle(self.selectedPhrase.translatedPhrase, for: .normal) self.translatedPhraseButton.sizeToFit() self.translatedPhraseButton.titleEdgeInsets = UIEdgeInse

我在屏幕上有一个按钮。UIButton上没有宽度限制。我喜欢我的UIButton扩展到指定的文本。但结果是:

以下是实施方案:

self.translatedPhraseButton.setTitle(self.selectedPhrase.translatedPhrase, for: .normal)
self.translatedPhraseButton.sizeToFit()
self.translatedPhraseButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
self.translatedPhraseButton.layer.cornerRadius = 10.0
self.translatedPhraseButton.layer.masksToBounds = true
self.translatedPhraseButton.backgroundColor = UIColor(fromHexString: "2aace3")

尝试创建一个临时标签,然后将按钮的大小设置为该标签的大小

let label = UILabel()
label.text = button.titleLabel?.text
label.font = button.titleLabel?.font
label.sizeToFit()

yourButton.frame.size = label.frame.size
此外,您还可以调整按钮的
标题标签
,以缩小文本以使其适合:

button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.5
问题: 文本被截断的原因是由于以下行:

self.translatedPhraseButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
您已将10.0填充添加到标题标签,这将导致文本截断

解决方案: 我使用了Swift 3(如果需要,将其更改为Swift 2并不困难)

按钮: 援引:
因此,我最终通过使用一行代码解决了我的问题:

 self.translatedPhraseButton.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 0.0, right: 15.0) 

获取字符串大小并重置帧。请看,我不认为这将是必要的,因为UIButton使用固有的内容大小,因此它应该根据内容调整自身大小。不,按钮不会调整大小,您应该重置框架或校准sizeToFit方法!看起来intrinsicContentSize仅适用于系统类型按钮。即使我在titleEdgeInsets后调用sizeToFit,它也不会调整大小。这真的很奇怪:(谢谢!我想接下来的问题是如何在UIButton的左右两侧添加额外的填充。如我的回答所示,只需创建一个自定义UIButton类,并将
intrinsicContentSize
和10覆盖到原始宽度。这样按钮宽度就会变宽10(通过提供您想要的填充)谢谢!这是做这么简单事情的唯一方法!我能够通过self.translatedPhraseButton.contentEdgeInsets=UIEdgeInsets(顶部:0.0,左侧:15.0,底部:0.0,右侧:15.0)将其添加为一个答案以使其他人受益
let translatedPhraseButton = RoundedCornerButton()
translatedPhraseButton.setTitle("haskjhdjk", for: .normal)

view.addSubview(translatedPhraseButton)

translatedPhraseButton.translatesAutoresizingMaskIntoConstraints = false

translatedPhraseButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
translatedPhraseButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
 self.translatedPhraseButton.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 0.0, right: 15.0)