-2.7 C
New York
Wednesday, January 8, 2025

ios – Place NSAttributedString – Stack Overflow


I’m attempting to maneuver the textual content like this picture:
https://i.ibb.co/56NvRXz/Skjermbilde-2025-01-07-kl-02-55-24.png

Utilizing a easy model with string = “4 / 23”

That is the label code:

non-public let numberLabel: UILabel = {
    let label = UILabel()
    label.textAlignment = .middle
    label.font = UIFont.systemFont(ofSize: 18, weight: .daring)
    label.textColor = .black
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 0
    return label
}()

override init(body: CGRect) {
    tremendous.init(body: body)
    addSubview(numberLabel)
    backgroundColor = UIColor.systemGray5
    layer.borderColor = UIColor.black.cgColor
    layer.borderWidth = 1.0
    NSLayoutConstraint.activate([
        numberLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
        numberLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
    ])
    
    // Set the numberLabel to fill the whole cell
    NSLayoutConstraint.activate([
        numberLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
        numberLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        numberLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        numberLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
    ])
}

The label is positioned inside a UICollectionView.
I set the label like this:
numberLabel.attributedText = createFormattedString(for: quantity)
numberLabel.backgroundColor = .purple

Right here is the operate:

    func createFormattedString(for string: String) -> NSAttributedString {
    // If the string incorporates a "https://stackoverflow.com/", deal with the particular case
    if let slashRange = string.vary(of: "/") {
    let topPart = string[slashRange.upperBound...]  // Every little thing after "https://stackoverflow.com/"
    let bottomPart = string[..

This is the output I am getting:
https://i.ibb.co/vzH7Kfp/Skjermbilde-2025-01-07-kl-02-59-34.png

Why is the 4 going outside?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles