简体   繁体   中英

iOS UILabel size issue

I searched for 4 hours before writing my question, none of the answers I saw online solve this issue.

I'm working on an iOS app, and in the storyboard, when I'm using a UILabel, no matter what I do, there's always extra padding on top, this is causing me a big issue since I'm trying to have a pixel perfect design.

I still don't understand where this is coming from, I tried using Plain text, and I tried attributed strings, both still give this extra padding:

Screenshot: http://imgur.com/Fldcodl

I tried to subclass the label with the following:

var textInsets = UIEdgeInsets.zero {
    didSet { invalidateIntrinsicContentSize() }
}


override var bounds:CGRect {
    get {
        return super.bounds
    }
    set {
        super.bounds = newValue
        if (self.preferredMaxLayoutWidth != super.bounds.size.width) {
            self.preferredMaxLayoutWidth = super.bounds.size.width;
            self.setNeedsUpdateConstraints()
        }

    }
}

override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
    let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
    let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                      left: -textInsets.left,
                                      bottom: -textInsets.bottom,
                                      right: -textInsets.right)
    return UIEdgeInsetsInsetRect(textRect, invertedInsets)
}

override func drawText(in rect: CGRect) {
    super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
}

Even with the values for top left right bottom set to 0 I still get this annoying top padding.

Any idea how to solve this?

Thanks!

Assuming you are wanting to remove the white space around your label (not entirely clear from your question).

Your label has a yellow background, the margin you're trying to remove is outside the label, so no amount of subclassing will remove it.

The way you add the label to the screen (in code or Interface Builder, via constraints or frames) is what defines those margins, that is the what you need to adjust to fix your margins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM