简体   繁体   English

将按钮的字体大小设置为最大以适合宽度和高度

[英]Set fontsize of button to maximum to fit in width and height

I'm creating an app for iOS using Xcode and Swift. 我正在使用Xcode和Swift为iOS创建一个应用程序。

I have a button, that fills the screen in width and has a height proportional to the root view. 我有一个按钮,它在屏幕上占满整个屏幕的宽度,并且高度与根视图成比例。 I want the text of the button to be as big as possible while still fitting both in width and in height. 我希望按钮的文本尽可能大,同时仍要同时容纳宽度和高度。 I tried setting a really big font size(100), lines to 1 and adjustsFontSizeToFitWidth to true. 我尝试设置一个非常大的字体大小(100),将行数设置为1,并将adjustsFontSizeToFitWidth设置为true。 The effect was, that it makes the font size to fill width and if the text doesn't fit any more (as it is the case in portrait mode on my tablet) it replaces part of the text with "..." 效果是,它使字体大小变为宽度,并且如果文本不再适合(如平板电脑上的纵向模式),它将部分文本替换为“ ...”

Also in Landscape mode, while most of the text fits perfectly in height, the slash is bigger than the height and is partly outside the button (at the bottom). 同样在“横向”模式下,尽管大多数文本的高度都非常合适,但斜杠大于高度,并且部分位于按钮的外侧(底部)。

the best practice is to place label beneath button. 最佳做法是将标签放在按钮下方。 and make button transparent to fill all your label. 并使按钮透明以填充所有标签。 - do this with right constraints. -在正确的约束下执行此操作。 i wrote small video how to achive that - 我写了一些小视频,如何做到这一点-

https://www.screencast.com/t/u8gb4f5YaBd https://www.screencast.com/t/u8gb4f5YaBd

You have to use a transparent button and add a label behind that button. 您必须使用透明按钮,并在该按钮后面添加标签。 There is no other way then hit and try. 没有其他方法可以尝试。 You have to set the font and check if that is fit to your width or not. 您必须设置字体,然后检查字体是否适合您的宽度。 Here is some example of recursive function. 这是递归函数的一些示例。 You have to set label.lineBreakMode = .byCharWrapping and label.numberOflines = 0 您必须设置label.lineBreakMode = .byCharWrappinglabel.numberOflines = 0

func adjustSize() {
     let font = label.font
     label.font = UIFont(name: font!.fontName, size: font!.pointSize + 1)
     let constraintRect = UIScreen.main.bounds.size
     let boundingBox = label.text!.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: label.font], context: nil)
     if boundingBox.width < constraintRect.width {
        adjustSize()
     }
}

Potrait模式

风景模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM