Vertically align text within a UILabel (Note : Using AutoLayout)

前端 未结 17 2679
忘掉有多难
忘掉有多难 2020-12-23 02:24

I am Copying the same Question asked Before Question. I have tried the solutions given and was not able to solve it since sizetofit was not effective when I

17条回答
  •  梦毁少年i
    2020-12-23 02:41

    use this my class, you can change text alignment by contentMode.

    supported case: .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight

    Swift4

    import Foundation
    import UIKit
    
    @IBDesignable
    class UIAlignedLabel: UILabel {
    
        override func drawText(in rect: CGRect) {
            if let text = text as NSString? {
                func defaultRect(for maxSize: CGSize) -> CGRect {
                    let size = text
                        .boundingRect(
                            with: maxSize,
                            options: NSStringDrawingOptions.usesLineFragmentOrigin,
                            attributes: [
                                NSAttributedStringKey.font: font
                            ],
                            context: nil
                        ).size
                    let rect = CGRect(
                        origin: .zero,
                        size: CGSize(
                            width: min(frame.width, ceil(size.width)),
                            height: min(frame.height, ceil(size.height))
                        )
                    )
                    return rect
    
                }
                switch contentMode {
                case .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight:
                    let maxSize = CGSize(width: frame.width, height: frame.height)
                    var rect = defaultRect(for: maxSize)
                    switch contentMode {
                        case .bottom, .bottomLeft, .bottomRight:
                            rect.origin.y = frame.height - rect.height
                        default: break
                    }
                    switch contentMode {
                        case .right, .topRight, .bottomRight:
                            rect.origin.x = frame.width - rect.width
                        default: break
                    }
                    super.drawText(in: rect)
                default:
                    super.drawText(in: rect)
                }
            } else {
                super.drawText(in: rect)
            }
        }
    
    }
    

提交回复
热议问题