I ran into an issue where I needed to animate translating a label vertically the same distance of a textField's text height. In most cases just textField.bounds.heigt
but if the textField's height is bigger than the text height it will not be any good for me. So I need to know: How to calculate the line height of the string text from its UIFont
?
我遇到了一个问题,我需要设置动画来垂直翻译标签与textField的文本高度相同的距离。在大多数情况下只是textField.bounds.heigt,但如果textField的高度大于文本高度,那对我来说就不会有任何好处。所以我需要知道:如何从UIFont计算字符串文本的行高?
Regarding the duplicate: There's a little bit different of what I need. that answer(which I've referenced in my answer) get the total height depending on 1) the string 2) the width 3) the font. What I needed is one line height dpending only on the font.
关于副本:我需要的东西有点不同。答案(我在答案中引用)得到总高度取决于1)字符串2)宽度3)字体。我需要的是只有字体的一行高度。
2 个解决方案
#1
7
UIFont has a propperty lineHeight smth like this
UIFont有这样的属性lineHeight smth
if let font = _textView.font {
let height = font.lineHeight
}
where font it's your font
字体是你的字体
#2
3
I have been searching for a way to do that and find this answer where it has a String
extension to calculate the size for the string and a given font. I have modified it to do what I want (get the line height of text written using a font.):
我一直在寻找一种方法,并找到这个答案,它有一个字符串扩展,以计算字符串和给定字体的大小。我修改它来做我想要的(获取使用字体写入的文本的行高)。
extension UIFont {
var height:CGFloat {
let constraintRect = CGSize(width: CGFloat.max, height: CGFloat.max)
let boundingBox = "Anytext".boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self], context: nil)
return boundingBox.height
}
}
I hope this helps someone looking for it. (may be myself in the future).
我希望这有助于有人寻找它。 (未来可能是我自己)。
#1
7
UIFont has a propperty lineHeight smth like this
UIFont有这样的属性lineHeight smth
if let font = _textView.font {
let height = font.lineHeight
}
where font it's your font
字体是你的字体
#2
3
I have been searching for a way to do that and find this answer where it has a String
extension to calculate the size for the string and a given font. I have modified it to do what I want (get the line height of text written using a font.):
我一直在寻找一种方法,并找到这个答案,它有一个字符串扩展,以计算字符串和给定字体的大小。我修改它来做我想要的(获取使用字体写入的文本的行高)。
extension UIFont {
var height:CGFloat {
let constraintRect = CGSize(width: CGFloat.max, height: CGFloat.max)
let boundingBox = "Anytext".boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self], context: nil)
return boundingBox.height
}
}
I hope this helps someone looking for it. (may be myself in the future).
我希望这有助于有人寻找它。 (未来可能是我自己)。