-->

Space characters being removed from end of String

2020-07-02 09:01发布

问题:

I have the following code for a Table View Cell in Swift

    let rcap = cell.viewWithTag(613) as! UILabel
    rcap.text = "Capacity: \(room.capacity)  "  // I added space at the end

The space characters at the end of the string, are removed when shown on screen.

If I add space characters at the beginning of the string there is no issue.

At the moment I am using this 'full stop' hack, but it is not good enough:

rcap.text = "Capacity: \(room.capacity)   ."  

Any ideas?

I also tried:

rcap.text = "Capacity: \(room.capacity)  " + " "

回答1:

Adding a constraint to the label seems like the better solution to me. It allows you to define a well-defined distance between the label and the margin of the table view cell. The width of a space is dependent on the font and might even change if the text in the label is shrunk, causing non-aligned texts in the table view.

Having said that, you can prevent the trailing space from being removed by appending a "ZERO WIDTH NON-JOINER" character (U+200C):

rcap.text = "Capacity: \(room.capacity)  \u{200c}"

But I consider that more as a "trick" than the proper solution to the problem.

Update: It seems that this "trick" does not work any more in iOS 10, so a layout constraint should be used instead, as initially suggested.



回答2:

For 2020

This issue is critical when working with monospaced fonts and doing layout, such as, say, user codes which may have alignment spaces at the end in monospace.

\u{200c} does seem to work perfectly:

Please note that the solution of @MartinR does in fact work perfectly, today, 2020 A.D., iOS 13, Xcode 11.

.text = "FATTIE KODE " + reservation + reservation.neededTrailingSpaces + \u{200c}"

.text = "FATTIE KODE " + reservation + reservation.neededTrailingSpaces + \u{200c}"

.text = "FATTIE KODE " + reservation + reservation.neededTrailingSpaces + \u{200c}"

You can now absolutely normally set font sizes, etc etc. and it all works properly.


Bonus code sample!

Here's a simple UILabel that pads it out, so you need do nothing else:

class PaddyLabel: UILabel {

// pad always to 20 characters...

override var text: String? {
        get {
            return super.text
        }
        set {
            if newValue == nil {
                super.text = nil
                return
            }
            var t = newValue!
            while t.count < 20 { t += " " }
            t += "\u{200c}"
            super.text = t
        }
    }

So in the above three yellow examples, you would just do this

.text = "FATTIE KODE " + reservation

and not have to bother adding the needed spaces manually.


Note that even if you are not using monospace fonts, a typical real-world use case is when you want to "pile together" UILabels - imagine them being, say, one word each - and have the absolutely correct space between them regardless of font size etc, that is to say as if it's just the one sentence in the one UILabel.

The only way to actually do that is to have UILabel "actually include the space".


If it does not work in a future iOS...

Perhaps this will (again?) break in a future iOS.

The only other solution I know is this. To begin with, it's ridiculously hard to just add padding to a UILabel. It is explained here:

Adding padding manually to a UILabel?

How to actually reliably add damned padding to a UILabel

In fact, using a similar technique, it would be possible to force the extra width on one end using intrinsicContentSize , drawText and textRect. To know how much width to add, you would have to calculate that using a phantom example text, with the number of characters in question. Doing that calculation would call for the usual annoying techniques for calculating likely text rendering size. But because that sucks, fortunately we can use the amazing tip of @MartinR (as usual!)



回答3:

Try putting zero-width space instead of the period. It can be written using left Alt and 0173 on numeric keyboard. Or you can copy it here and delete the quotes: "­"

So your code for setting the text will look like this (with the zero-width space at the end):
rcap.text = "Capacity: \(room.capacity) ­"
Non-breaking space (\u{00a0}) should work too and its usage is as \u{200c}'s in Martin's and Fattie's answer



回答4:

I have created custom class for UILabel, take a look:

import UIKit

@IBDesignable class CustomLable: UILabel {
    @IBInspectable var topInset: CGFloat = 5.0
    @IBInspectable var bottomInset: CGFloat = 5.0
    @IBInspectable var leftInset: CGFloat = 7.0
    @IBInspectable var rightInset: CGFloat = 7.0

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)

    }

}

You can than assign a class to UILabel from Storyboard and provide space you need.



回答5:

rcap.text = String.localizedStringWithFormat("Capacity: %@ ", rrom.capacity)

try above code it may works



回答6:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@ .",numString]];

[str addAttributes:@{ NSForegroundColorAttributeName : label.backgroundColor } range:[str.string rangeOfString:@"."]];

label.attributedText = str;