2016-08-05 29 views
1

Es gibt einige Beispiele dafür, wie Sie in Swift ein Top Aligned-Label erstellen. Hier ist das für mich funktioniert:Wie erstellt man in Swift ein nach unten ausgerichtetes Etikett?

@IBDesignable class TopAlignedLabel: UILabel { 
    override func drawTextInRect(rect: CGRect) { 
     if let stringText = text { 
      let stringTextAsNSString = stringText as NSString 
      var labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max), 
       options: NSStringDrawingOptions.UsesLineFragmentOrigin, 
       attributes: [NSFontAttributeName: font], 
       context: nil).size 
      super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height))) 
     } else { 
      super.drawTextInRect(rect) 
     } 
    } 
    override func prepareForInterfaceBuilder() { 
     super.prepareForInterfaceBuilder() 
     layer.borderWidth = 1 
     layer.borderColor = UIColor.blackColor().CGColor 
    } 
} 

Ich versuche, dies zu ändern, um ein unten ausgerichtete Etikett zu schaffen, aber kämpfen, um das Richtige zu finden zu ändern. Jede Hilfe wird geschätzt!

Antwort

4

Ändern Sie diese Zeile:

super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height))) 

In diese:

super.drawTextInRect(CGRectMake(0, rect.size.height - labelStringSize.height, CGRectGetWidth(self.frame), ceil(labelStringSize.height))) 
1

die Lösung Update für SWIFT 3.0, vollständige Code wird:

import UIKit 

@IBDesignable class BottomAlignedLabel: UILabel { 
override func drawText(in rect: CGRect) { 
    if let stringText = text { 
     let stringTextAsNSString = stringText as NSString 
     let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude), 
                   options: NSStringDrawingOptions.usesLineFragmentOrigin, 
                   attributes: [NSFontAttributeName: font], 
                   context: nil).size 
     super.drawText(in: CGRect(x:0,y: rect.size.height - labelStringSize.height, width: self.frame.width, height: ceil(labelStringSize.height))) 
    } else { 
     super.drawText(in: rect) 
    } 
} 
override func prepareForInterfaceBuilder() { 
    super.prepareForInterfaceBuilder() 
    layer.borderWidth = 1 
    layer.borderColor = UIColor.clear.cgColor 
} 

}