2016-04-14 64 views
0

我想把一些文本放在CGRect的中心位置,该图像位于该图像的顶部。以下是一段代码:使用Swift的drawInRect文本对齐

 let textColor: UIColor = UIColor.whiteColor() 
     let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 17 
      )! 
     let textAlignment = NSTextAlignment.Center 

     let textFontAttributes = [ 
      NSFontAttributeName: textFont, 
      NSForegroundColorAttributeName: textColor, 
      NSTextAlignment: textAlignment 
      ] 

     myString.drawInRect(rect, withAttributes: textFontAttributes) 

问题在于文本对齐。当我把它写这样我得到一个错误:

Type of expression is ambiguous without more context

当我设置键和值类型[字符串:AnyObject]编译器再次抱怨:

Cannot convert value of type 'NSTextAlignment.Type' to expected dictionary key type 'String'

我理解。我研究了这两个小时,并没有找到任何最新的解决方案,而不是单一的云如何使用Swift写这个。

回答

3

NSTextAlignment不是有效的密钥。请注意其他密钥如何在Name中结束。请参阅文档NSFontAttributeNameNSForegroundColorAttributeName以查看有效密钥的列表。

而不是NSTextAlignment您需要使用NSParagraphStyleAttributeName这需要您创建一个NSParagraphStyle的实例。那就是你设置alignment.Center的地方。

let paragraphStyle = NSMutableParagraphStyle() 
paragraphStyle.alignment = .Center 
1

文本对齐属于段落样式。创建一个NSMutableParagraphStyle实例,并将其与密钥NSParagraphStyleAttributeName一起传递给属性。

let style = NSMutableParagraphStyle() 
style.alignment = .Center 
let textFontAttributes = [ 
      NSFontAttributeName: textFont, 
      NSForegroundColorAttributeName: textColor, 
      NSParagraphStyleAttributeName: style 
      ]