UIlabel顶格

来源:互联网 发布:淘宝店信誉怎么提高 编辑:程序博客网 时间:2024/05/16 17:33

新建一个继承uilabel的类,用它定义label,设置属性即可。


#import <UIKit/UIKit.h>


typedefenum : NSUInteger {

    VerticalAlignmentTop =0, // default

    VerticalAlignmentMiddle,

    VerticalAlignmentBottom,

} VerticalAlignment;


@interface MyLabel :UILabel


@property (nonatomic)VerticalAlignment verticalAlignment;


@end



#import "MyLabel.h"


@implementation MyLabel


/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    // Drawing code

}

*/



- (id)initWithFrame:(CGRect)frame {

   if (self = [superinitWithFrame:frame]) {

        self.verticalAlignment =VerticalAlignmentMiddle;

    }

    return self;

}


- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {

   _verticalAlignment = verticalAlignment;

    [selfsetNeedsDisplay];

}


- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {

   CGRect textRect = [supertextRectForBounds:bounds limitedToNumberOfLines:numberOfLines];

    switch (self.verticalAlignment) {

        caseVerticalAlignmentTop:

            textRect.origin.y = bounds.origin.y;

           break;

        caseVerticalAlignmentBottom:

            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;

           break;

        caseVerticalAlignmentMiddle:

            // 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 = [selftextRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];

    [superdrawTextInRect:actualRect];

}


@end


注意storyboard中label的类要绑定,牵线的属性也要改成自定义的类。

实现:

- (void)awakeFromNib{

    [self.titleLabelsetVerticalAlignment:VerticalAlignmentTop];

}


0 0
原创粉丝点击