Vertically align UILabel

前端 未结 10 1585
故里飘歌
故里飘歌 2020-12-31 10:34

I am trying to vertically align the text in the UILabel view of my app. The problem is that I want the text to be vertically aligned to the top and the size of the label to

10条回答
  •  遥遥无期
    2020-12-31 10:52

    In Swift, JRC’s solution of subclassing UILabel, overriding drawTextInRect and conforming to UIViewContentMode would look like this:

    class AlignableUILabel: UILabel {
    
        override func drawText(in rect: CGRect) {
    
            var newRect = CGRect(x: rect.origin.x,y: rect.origin.y,width: rect.width, height: rect.height)
            let fittingSize = sizeThatFits(rect.size)
    
            if contentMode == UIViewContentMode.top {
                newRect.size.height = min(newRect.size.height, fittingSize.height)
            } else if contentMode == UIViewContentMode.bottom {
                newRect.origin.y = max(0, newRect.size.height - fittingSize.height)
            }
    
            super.drawText(in: newRect)
        }
    
    }
    

    Implementing is simply a matter of:

    yourLabel.contentMode = UIViewContentMode.top
    

    For me, it worked like a charm.

提交回复
热议问题