UILabel顶端对齐

作者: Levi_ | 来源:发表于2015-03-26 22:10 被阅读1608次

    苹果并未提供Label顶端对齐的设置,但是我们经常会有这种需求,现提供一个方法。

    //.h文件
    typedef enum VerticalAlignment {
        VerticalAlignmentTop,
        VerticalAlignmentMiddle,
        VerticalAlignmentBottom,
    } VerticalAlignment;
    
    @interface VerticallyAlignedLabel : UILabel {
    @private
        VerticalAlignment verticalAlignment_;
    }
    
    @property (nonatomic, assign) VerticalAlignment verticalAlignment;
    
    //.m文件
    @synthesize verticalAlignment = verticalAlignment_;
    
    - (id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            self.verticalAlignment = VerticalAlignmentMiddle;
        }
        return self;
    }
    
    - (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
        verticalAlignment_ = verticalAlignment;
        [self setNeedsDisplay];
    }
    
    - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
        CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
        switch (self.verticalAlignment) {
            case VerticalAlignmentTop:
                textRect.origin.y = bounds.origin.y;
                break;
            case VerticalAlignmentBottom:
                textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
                break;
            case VerticalAlignmentMiddle:
                // Fall through.
            default:
                textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
        }
        return textRect;
    }
    
    -(void)drawTextInRect:(CGRect)requestedRect {
        CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
        [super drawTextInRect:actualRect];
    }
    

    除了可以顶端对齐还可以底端对齐,但估计这种需求不多。
    调用时只需继承这个label,然后调用

    [label setContentMode:UIViewContentModeTop];
    

    是不是很简单呢?

    相关文章

      网友评论

      • 断忆残缘:label.verticalAlignment = VerticalAlignmentTop
        这样才能正确设置
      • c49f19c51208:感谢分享

      • iHTCboy:亲,感谢分享,如果能注释一下代码或好,因为现在学习时间太小了

      本文标题:UILabel顶端对齐

      本文链接:https://www.haomeiwen.com/subject/uiqnxttx.html