How to set top-left alignment for UILabel for iOS application?

后端 未结 21 1540
傲寒
傲寒 2020-12-04 07:54

I have added one label in my nib file, then its required to have top-left alignment for that lable. As I am providing text at runtime so its not sure that how much lines the

21条回答
  •  忘掉有多难
    2020-12-04 08:17

    Swift 2.0: : Using UILabel Extension

    Make constant enum values in a empty Swift file.

    //  AppRef.swift
    
    import UIKit
    import Foundation
    
    enum UILabelTextPositions : String {
    
     case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
     case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
     case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"
    
    }
    

    Using UILabel Extension:

    Make a empty Swift class and name it. Add the following.

    //  AppExtensions.swift
    
    import Foundation
    import UIKit
    
        extension UILabel{ 
         func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
         {
          let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)
    
          switch positionIdentifier
          {
          case "VerticalAlignmentTop":
           sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
           break;
    
          case "VerticalAlignmentMiddle":
           sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
            rect.size.width, rect.size.height);
           break;
    
          case "VerticalAlignmentBottom":
           sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
           break;
    
          default:
           sampleLabel!.frame = bounds;
           break;
          }
          return sampleLabel!
    
         }
        }
    

    Usage :

    myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)
    

提交回复
热议问题