apploft / ExpandableLabel

A simple UILabel subclass that shows a tappable link if the content doesn't fit the specified number of lines
MIT License
466 stars 126 forks source link

textAlignment property is not working #84

Open auro-krishna opened 4 years ago

auro-krishna commented 4 years ago

textAlignment is not updating always aligns to left, How to fix this?

mdeora commented 4 years ago

did you find a fix for this?

auro-krishna commented 3 years ago

@mdeora Not yet

Omeesh commented 3 years ago

I fixed the issue by changing some code in Library

  1. Open the "ExpandableLabel.swift" file.
  2. Initialise a variable in the class. i.e open var customTextAlignment: NSTextAlignment?
  3. Replace copyWithParagraphAttribute function with following function

    func copyWithParagraphAttribute(_ font: UIFont,_ alignment: NSTextAlignment) -> NSAttributedString {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = 1.05
        paragraphStyle.alignment = alignment
        paragraphStyle.lineSpacing = 0.0
        paragraphStyle.minimumLineHeight = font.lineHeight
        paragraphStyle.maximumLineHeight = font.lineHeight
    
        let copy = NSMutableAttributedString(attributedString: self)
        let range = NSRange(location: 0, length: copy.length)
        copy.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
        copy.addAttribute(.baselineOffset, value: font.pointSize * 0.08, range: range)
        return copy
    }
  4. Replace the attributedText variable with following code
    open override var attributedText: NSAttributedString? {
        set(attributedText) {
            if let attributedText = attributedText?.copyWithAddedFontAttribute(font).copyWithParagraphAttribute(font, self. customTextAlignment ?? .left),
                attributedText.length > 0 {
                self.collapsedText = getCollapsedText(for: attributedText, link: (linkHighlighted) ? collapsedAttributedLink.copyWithHighlightedColor() : self.collapsedAttributedLink)
                self.expandedText = getExpandedText(for: attributedText, link: (linkHighlighted) ? expandedAttributedLink?.copyWithHighlightedColor() : self.expandedAttributedLink)
                super.attributedText = (self.collapsed) ? self.collapsedText : self.expandedText
            } else {
                self.expandedText = nil
                self.collapsedText = nil
                super.attributedText = nil
            }
        }
        get {
            return super.attributedText
        }
    }
  5. Clean the build folder
  6. Set the alignment of label in your class label.customTextAlignment = .center