經過反覆試驗,我找到了一個解決此問題的方法,即以更小的間隔1縮小字體,以便更好地適應標籤的寬度。
extension UILabel {
func shrinkToFitWidth(margin: CGFloat?) {
// margin parameter will shrink the font by a certain amount more than necessary.
// Use this if you want a label with smaller text on a bigger background. Otherwise, use 0.
var initialSize : CGSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
if initialSize.width > self.frame.size.width
{
while initialSize.width > self.frame.size.width
{
self.font = self.font.fontWithSize(self.font.pointSize - 1)
initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
}
} else {
while initialSize.width < self.frame.size.width
{
self.font = self.font.fontWithSize(self.font.pointSize + 1)
initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
}
// went 1 point too large so compensate here
self.font = self.font.fontWithSize(self.font.pointSize - 1)
}
self.font = self.font.fontWithSize(self.font.pointSize - margin!)
}
func shrinkToFitHeight(margin: CGFloat?) {
// margin parameter will shrink the font by a certain amount more than necessary.
// Use this if you want a label with smaller text on a bigger background. Otherwise, use 0.
var initialSize : CGSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
if initialSize.height > self.frame.size.height
{
while initialSize.height > self.frame.size.height
{
self.font = self.font.fontWithSize(self.font.pointSize - 1)
initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
}
} else {
while initialSize.height < self.frame.size.height
{
self.font = self.font.fontWithSize(self.font.pointSize + 1)
initialSize = self.text!.sizeWithAttributes([NSFontAttributeName : self.font])
}
// went 1 point too large so compensate here
self.font = self.font.fontWithSize(self.font.pointSize - 1)
}
self.font = self.font.fontWithSize(self.font.pointSize - margin!)
}
注意的是,爲了實現這一點,應該在一個視圖控制器的viewDidLayoutSubviews
方法,以便將已應用的約束調用。
乾杯!
是兩個例子的邊緣到邊緣的標籤嗎?當你有一個很大的單詞時,你能添加兩個更多的截圖嗎? – Korpel
@Korpel標籤不在彩色背景上,顏色是標籤的背景。那有意義嗎? – Joshua
ofc它。你是否嘗試過使用較小的標籤,而不是使用標籤的大小?改爲將其轉換爲UIView,讓標籤佔用較小的空間,然後再試一次? – Korpel