从字符串末尾删除空格字符-UILabel Swift [英] Space characters being removed from end of String - UILabel Swift

查看:75
本文介绍了从字符串末尾删除空格字符-UILabel Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Swift中的一个表格视图单元,我有以下代码

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.

目前,我正在使用这种句号" hack,但这还不够好:

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

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

有什么想法吗?

我也尝试过:

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

推荐答案

向标签添加约束似乎对我来说是更好的解决方案.它允许您定义标签和标签之间的明确定义的距离.表格视图单元格的边距.空格的宽度取决于字体,并且如果标签中的文本缩小,甚至会发生变化,从而导致标签中的文本未对齐.表格视图.

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.

话虽如此,您可以防止尾随空格被通过添加零宽度非JOINER"字符(U + 200C)删除:

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.

更新:在iOS 10中,此技巧"似乎不再起作用,因此应按照最初的建议使用布局约束.

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.

这篇关于从字符串末尾删除空格字符-UILabel Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆