2015-12-03 64 views
2

我已經使用Swift創建了一個iOS應用程序。現在我有一個問題想讓我的文本中心+一個標籤的底部和另一個標籤的中心+頂部。有可能嗎?文字底部+中心UILabel iOS Swift

我想這

//Here learnItem is my label. 
    let constraintSize: CGSize = CGSizeMake(learnItem.frame.size.width, CGFloat(MAXFLOAT)) 
    let textRect: CGRect = learnItem.text!.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: learnItem.font], context: nil) 
      learnItem.drawRect(textRect); 

它不會影響任何東西。所以也許它是一個wromg代碼。我也看到了

learnItem.textAlignment = .Center 

center, justified, left, natural, right的選項。但那不是我想要的。

請幫我一下如何讓我的文本中心+底部和中心+頂部

回答

5

爲了做到這一點,您應該重寫drawTextInRect方法。

// MARK: - BottomAlignedLabel 

@IBDesignable class BottomAlignedLabel: UILabel { 

    // MARK: Lifecycle 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func drawText(in rect: CGRect) { 

     guard text != nil else { 
      return super.drawText(in: rect) 
     } 

     let height = self.sizeThatFits(rect.size).height 
     let y = rect.origin.y + rect.height - height 
     super.drawText(in: CGRect(x: 0, y: y, width: rect.width, height: height)) 
    } 
} 

對於頂部對齊y應該0

如果您使用故事板,則使用此代碼的最簡單方法就是更改故事板中標籤的類。

+0

我忘了提及我也看到了這段代碼。並不知道如何使用它。如果我添加這個,我怎麼能連接這個與我的標籤。也許愚蠢的問題。但不知道如何做到這一點? – Amsheer

+0

最簡單的方法是將您的標籤在故事板中的等級更改爲'BottomAlignedLabel' –

+0

謝謝。從昨天開始,我一直在尋找這個確切的代碼。謝謝你幫我弄清楚。 – Amsheer