0

So I have a normal UILabel inside UIView with some words inside. It is a 3 lines label and has .adjustsFontSizeToFitWidth = true

Most of the time it works fine but in some cases there is hyphenation of words, like this:

Don't want like this

But in other combinations of letters it is like i want/need, it doesn't hyphen and just adjust the size:

That is what needed

What I need is to force UILabel not to break/hyphen words and instead prefer adjusting the size. Line breaks modes don't do much here. Is there a way that I am missing to turn off the word hyphen or breaking? I also have tried to find out how to check if the word was breaked but was unable to find it either so I can adjust the number of lines for example.

Edit: here is playground code to have a look:

import Foundation
import UIKit
import PlaygroundSupport

public class Card: UIView {

var label2: UILabel!

public init(frame: CGRect, withText: String) {
    super.init(frame: frame)
    
    self.backgroundColor = UIColor(red: 0.313, green: 0.89, blue: 0.76, alpha: 1.000)
    
    label2 = UILabel(frame: CGRect(x: bounds.width / 2 - 115, y: (bounds.height/2 - 90), width: 230, height: 180))
    
    label2.textAlignment = .center
    
    label2.text = "stepper; rotory; revolutionizing"
    label2.font = UIFont.boldSystemFont(ofSize: 60)
    label2.textColor = UIColor.white
    
    label2.adjustsFontSizeToFitWidth = true
    label2.translatesAutoresizingMaskIntoConstraints = false
    
    label2.numberOfLines = 0
    
    self.addSubview(label2)
    
    //        label2.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    //        label2.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -50).isActive = true
    //        label2.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 50).isActive = true
    //        label2.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    
    
    
}

required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}




}


let card = Card(frame: CGRect(x: 10, y: 30, width: 280, height: 200),         withText: "💜")

let page = PlaygroundPage.current

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 500))
view.backgroundColor = UIColor.white
view.addSubview(card)


page.liveView = view

1 Answer 1

1

There're two way to do it, the first is :

yourLabel.text = "stepper;\nrotor;\nrevolutioning;"

just add \n at last of any word...

the second: create 3 label, with relative text, and put it in a vertical stackView...

let yourLabel1 = UILabel()
let yourLabel2 = UILabel()
let yourLabel3 = UILabel()

yourLabel1.text = "stepper;"
yourLabel2.text = "rotor;"
yourLabel3.text = "revolutioning;"

after that create stack view and add the labels

let stackView = UIStackView(arrangedSubviews: [label1, label2, label3])
stackView.axis = .vertical
stackView.distribution = .fillEqually
... etc etc

set stackView constraints and you're good to go

UPDATE FOR YOUR COMMENTS:

yourLabel.text = "stepper; rotor; revolutioning; xxxxxxx; xx; xxxxxxxxxxxxxx; xxxxx; xxxxxxxxxxxx"
yourLabel.font = .systemFont(ofSize: 40, weight: .semibold)
yourLabel.textColor = .black
yourLabel.adjustsFontSizeToFitWidth = true;
yourLabel.minimumScaleFactor = 0.2;
yourLabel.numberOfLines = 0;
yourLabel.translatesAutoresizingMaskIntoConstraints = false
    
view.addSubview(yourLabel)
yourLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
yourLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50).isActive = true
yourLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50).isActive = true
yourLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

SPECIFIC UPDATE add this extension:

extension UILabel{

func adjustedFont()->UIFont {
    let attributes: [NSAttributedString.Key: Any] = [.font: font as Any]
    let attributedString = NSAttributedString(string: text ?? "", attributes: attributes)
    let drawingContext = NSStringDrawingContext()
    drawingContext.minimumScaleFactor = minimumScaleFactor

    attributedString.boundingRect(with: bounds.integral.size, options: .usesLineFragmentOrigin, context: drawingContext)

    let fontSize = font.pointSize * drawingContext.actualScaleFactor

    return font.withSize(fontSize)
}

func fitLabelWords(){
    layoutIfNeeded()
    let scaledFont = self.adjustedFont()
    let currentFont = scaledFont
    if let txt = text,
        let maxString = txt.components(separatedBy: " ").max(by: {$1.count > $0.count})?.replacingOccurrences(of: "\n", with: ""){
        let maxFontSize: CGFloat = currentFont.pointSize
        let minFontSize: CGFloat = 5.0

        var maxS = maxFontSize
        var minS = minFontSize
        let height = currentFont.lineHeight
        let constraintSize = CGSize(width: .greatestFiniteMagnitude, height: height)
        var sizedFont = currentFont
        while(minS <= maxS){
            let currentSize = (minS + maxS) / CGFloat(2)
            sizedFont = currentFont.withSize( CGFloat(currentSize) )

            let text = NSMutableAttributedString(string:maxString, attributes:[NSAttributedString.Key.font:sizedFont])

            let textRect = text.boundingRect(with: constraintSize, options: [.usesLineFragmentOrigin], context: nil).integral
            let labelSize = textRect.width

            //1 is a fudge factor
            if labelSize == ceil(self.bounds.width - 1){
                break
            }else if labelSize > ceil(self.bounds.width - 1){
                maxS = currentSize - 0.1
            }else{
                minS = currentSize + 0.1
            }
        }

        if sizedFont.pointSize < currentFont.pointSize{
            self.font = sizedFont
        }
    }
 }
}

set your label like this:

label2 = UILabel(frame: CGRect(x: view.bounds.width / 2 - 115, y: (view.bounds.height/2 - 90), width: 230, height: 180))
    
label2.textAlignment = .center
label2.text = "stepper; rotory; revolutionizing; skfghjkadsghasdg;"
label2.numberOfLines = 0
label2.font = UIFont.boldSystemFont(ofSize: 60)
label2.textColor = .white
label2.adjustsFontSizeToFitWidth = true
label2.minimumScaleFactor = 0.3
label2.fitLabelWords()
    
 view.addSubview(label2)
8
  • Thank you very much for your answer but I think that is not going to work, the problem is there can be an arbitrary number of words for example 2, 4, or 6, maybe not more but still, that is not going to work - in the first case, I just can't have 6 lines. And the second example can be even more problematic because different views can have different scaling then? Maybe I should have specified that this should fit in given height/width constraints (as in the picture for example) Commented Sep 11, 2020 at 13:57
  • Okay maybe in the first case it will fit 7 lines in given height by scaling the lines but in that case, there will be a word per line which is not a prefered case anyway. What I would like to have is only scaling without any brakes of the words. So if any word need to be hyphened it just adjust the scale and not hyphen the word, for now it is decide per case basis how it wants to behave:) Commented Sep 11, 2020 at 14:01
  • Try to add this to your label: yourlabel.adjustsFontSizeToFitWidth = true; yourlabel.minimumScaleFactor = 0.2; yourlabel.numberOfLines = 0;
    – Fabio
    Commented Sep 11, 2020 at 14:06
  • I have added the playground page, can you please have a look? The problem is that this appears only in some edge cases so if the view is a bit smaller or only one letter is added it can start behaving like this. Commented Sep 11, 2020 at 14:50
  • 1
    I update my answer, Take a look to SPECIFIC UPDATE...
    – Fabio
    Commented Sep 11, 2020 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.