天天看点

iOS常用方法——一个好用的获取View的位置和大小的类

在写代码的时候我们如果用frame进行布局的话,经常会用到像self.view.frame.size.width这样的语句来获取我们想要的位置或者大小的值,这个语句调用的时候很繁杂,下面是我封装的一个类,很简洁的代码就可拿到自己想要的值。

给UIVIew添加一个分类,因为UI基本都继承自UIView,写在UIVIew的分类中UI类都可调用。

#import <UIKit/UIKit.h>

@interface UIView (MYMargin)

@property(nonatomic,assign,readonly) float mLeft;

@property(nonatomic,assign,readonly) float mRight;

@property(nonatomic,assign,readonly) float mTop;

@property(nonatomic,assign,readonly) float mBottom;

@property(nonatomic,assign,readonly) float mWidth;

@property(nonatomic,assign,readonly) float mHeight;

@end
           
#import "UIView+MYMargin.h"

@implementation UIView (MYMargin)

-(float)mLeft{
    return self.frame.origin.x;
}

-(float)mRight{
    return self.frame.origin.x + self.frame.size.width;
}

-(float)mTop{
    return self.frame.origin.y;
}

-(float)mBottom{
    return self.frame.origin.y + self.frame.size.height;
}

-(float)mWidth{
    return self.frame.size.width;
}

-(float)mHeight{
    return self.frame.size.height;
}

@end
           

举个?,获取label的宽:

是不是简单了很多呢,调用也很方便。