How to align UILabel text from bottom?

后端 未结 10 1500
盖世英雄少女心
盖世英雄少女心 2021-02-03 19:08

How the UILabel can be aligned from bottom. Let say, my label can hold three line of text.If the input text is single line, then this line should come bottom of the

相关标签:
10条回答
  • 2021-02-03 20:03

    Another option: use one label for your background color, I call this one originalLabel, and another for the text, called textLabel in my example. Then calculate the height and Y coordinate for textLabel:

    [textLabel sizeToFit];
    int height = textLabel.frame.size.height;
    int yCoord = originalLabel.frame.origin.y + 
              originalLabel.frame.size.height - height;
    textLabel.frame = CGRectMake( originalLabel.frame.origin.x, yCoord,
              textLabel.frame.size.width, height);
    
    0 讨论(0)
  • 2021-02-03 20:04
    1. use autoLayout)
    textLabel.numberOfLines = 0
    textLabel.textAlignment = .center
    
    textLabel.topAnchor.constraint(greaterThanOrEqualTo: sView.topAnchor).isActive = true
    textLabel.leadingAnchor.constraint(equalTo: sView.leadingAnchor).isActive = true
    textLabel.trailingAnchor.constraint(equalTo: sView.trailingAnchor).isActive = true
    textLabel.bottomAnchor.constraint(equalTo: sView.bottomAnchor).isActive = true
    
    0 讨论(0)
  • 2021-02-03 20:04

    You can subclass UILabel and overriding the method :

    - (void)drawTextInRect:(CGRect)rect
    

    call super drawTextInRect with the rect where you want to use.

    0 讨论(0)
  • 2021-02-03 20:07

    Swift 4.2 version using the contentMode property to set top and bottom:

    class VerticalAlignedLabel: UILabel {
        
        override func drawText(in rect: CGRect) {
            var newRect = rect
            switch contentMode {
            case .top:
                newRect.size.height = sizeThatFits(rect.size).height
            case .bottom:
                let height = sizeThatFits(rect.size).height
                newRect.origin.y += rect.size.height - height
                newRect.size.height = height
            default:
                ()
            }
            
            super.drawText(in: newRect)
        }
    }
    

    Then setup your label like that:

    let label = VerticalAlignedLabel()
    label.contentMode = .bottom
    
    0 讨论(0)
提交回复
热议问题