在我的应用程序中,我正在使用ActiveLabel fram Github

在这种情况下,我的标签不会在UILabel的中间显示文本。如果我使用普通的UILabel,它可以正常工作,但是将其设置为ActiveLabel时,它会像这样。
ios - UILabel垂直对齐-LMLPHP

(图像是在运行时拍摄的)

我认为这是某种与对齐方式配合使用的代码:

/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
    let mutAttrString = NSMutableAttributedString(attributedString: attrString)

    var range = NSRange(location: 0, length: 0)
    var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)

    let paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
    if let lineSpacing = lineSpacing {
        paragraphStyle.lineSpacing = CGFloat(lineSpacing)
    }

    attributes[NSParagraphStyleAttributeName] = paragraphStyle
    mutAttrString.setAttributes(attributes, range: range)

    return mutAttrString
}

ActiveLabel.swift

ActiveType.swift

任何想法,我怎么能像这样在中间:
ios - UILabel垂直对齐-LMLPHP

(图片来自 Storyboard )

最佳答案

ActiveLabel.swift中,将drawTextInRect方法替换为

public override func drawTextInRect(rect: CGRect) {
        let range = NSRange(location: 0, length: textStorage.length)

        textContainer.size = rect.size

        let usedRect = layoutManager.usedRectForTextContainer(textContainer)

        let glyphOriginY = (rect.height > usedRect.height) ? rect.origin.y + (rect.height - usedRect.height) / 2 : rect.origin.y
        let glyphOrigin = CGPointMake(rect.origin.x, glyphOriginY)

        layoutManager.drawBackgroundForGlyphRange(range, atPoint: glyphOrigin)
        layoutManager.drawGlyphsForGlyphRange(range, atPoint: glyphOrigin)
    }

我也用https://github.com/rishi420/ActiveLabel.swift fork 了仓库

如果您下载存储库,请记住将verticalTextAlignmentCenter设置为true

关于ios - UILabel垂直对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34302407/

10-10 04:49