如何在Swift iOS8中正确获取字符串的宽度?

时间:2016-03-08 16:12:13

标签: objective-c iphone swift ios8

我已经阅读了很多有关此事的SO帖子,但找不到任何有效的帖子。

我的代码:

let englishTextSize    = englishString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14)])
let englishLabel       = UILabel(frame: CGRectMake(self.view.center.x, 150, englishTextSize.width, englishTextSize.height))

此代码段会在文本周围生成省略号,从而避免宽度不够大。

文本本身使用了许多模糊的字符,如:

svarūpe-'vasthānam

但我无法想象将它扔掉那么多。打开Swift或Obj-C中的任何提示,但最好是Swift!

4 个答案:

答案 0 :(得分:4)

您的代码可以像这样简单:

Private Sub ComboBox1_Enter()

On Error Resume Next
Dim rrange As Range
Dim VisibleRange As Range
Dim rcell As Object

Set rrange = Sheets("Project details").Range("A2:A150")

Dim byCSMCoprId As String 'corp id goes into criteria for autofilter.
byCSMCoprId = TextBox1.Text
On Error GoTo Error_Handler
With Sheets("Project details").Range("A1:M1")
    .autofilter field:=2, Criteria1:=byCSMCoprId
    .autofilter field:=7, Criteria1:=""
End With
Set VisibleRange = rrange.SpecialCells(xlCellTypeVisible)
For Each rcell In VisibleRange
        ComboBox1.AddItem rcell
Next
Error_Handler:
If Err.Number = 1004 And Err.Description = "No cells were found." Then GoTo Message:

Message:
    MsgBox "No cells were found"
End Sub

答案 1 :(得分:2)

取决于属性

Devise::Mailer.layout

答案 2 :(得分:2)

下面的代码对我来说非常合适。希望它能为你提供帮助......

    let name = "Statue of liberty"
    let size = (name as NSString).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)])

答案 3 :(得分:0)

无需自己计算宽度。您可以使用sizeToFit使宽度和高度适合文本,然后将框架更改为您想要的高度和原点。

类似的东西:

[englishLabel sizeToFit];
[parentView addSubview:englishLabel];
englishLabel.center = [parentView convertPoint:parentView.center
                                  fromView:parentView.superview];