先说说该分类名字中”FG”以及代码中”fg”的由来,两者都是取自博主的名字昵称,无其他意义,请放心使用!
这是一个自定义快速获取控件属性的分类,目的是摒弃平常开发中冗长的代码结构,举个例子,之前,我们获取某个控件 view 的宽度和高度的代码如下:
self.view.frame.size.width;
self.view.frame.size.height;
而在引用该分类后,代码的简洁程度明显增强:
self.view.fg_width;
self.view.fg_height;
分类中提供了包括控件的 x, y 坐标,宽高,center_x, center_y,控件右侧值以及控件底端值等属性。给控件 frame 的计算带来了极大的便利,使代码更加简短易懂。
实现原理较简单,下面贴出源码以供学习参考:
UIView+FGFrame.h 文件:
#import <UIKit/UIKit.h>
@interface UIView (FGFrame)
@property (nonatomic, assign) CGFloat fg_width;
@property (nonatomic, assign) CGFloat fg_height;
@property (nonatomic, assign) CGFloat fg_x;
@property (nonatomic, assign) CGFloat fg_y;
@property (nonatomic, assign) CGFloat fg_centerX;
@property (nonatomic, assign) CGFloat fg_centerY;
@property (nonatomic, assign) CGFloat fg_right;
@property (nonatomic, assign) CGFloat fg_bottom;
@end
UIView+FGFrame.m 文件:
#import "UIView+FGFrame.h"
@implementation UIView (FGFrame)
- (CGFloat)fg_width
{
return self.frame.size.width;
}
- (CGFloat)fg_height
{
return self.frame.size.height;
}
- (void)setFg_width:(CGFloat)fg_width
{
CGRect frame = self.frame;
frame.size.width = fg_width;
self.frame = frame;
}
- (void)setFg_height:(CGFloat)fg_height
{
CGRect frame = self.frame;
frame.size.height = fg_height;
self.frame = frame;
}
- (CGFloat)fg_x
{
return self.frame.origin.x;
}
- (void)setFg_x:(CGFloat)fg_x
{
CGRect frame = self.frame;
frame.origin.x = fg_x;
self.frame = frame;
}
- (CGFloat)fg_y
{
return self.frame.origin.y;
}
- (void)setFg_y:(CGFloat)fg_y
{
CGRect frame = self.frame;
frame.origin.y = fg_y;
self.frame = frame;
}
- (CGFloat)fg_centerX
{
return self.center.x;
}
- (void)setFg_centerX:(CGFloat)fg_centerX
{
CGPoint center = self.center;
center.x = fg_centerX;
self.center = center;
}
- (CGFloat)fg_centerY
{
return self.center.y;
}
- (void)setFg_centerY:(CGFloat)fg_centerY
{
CGPoint center = self.center;
center.y = fg_centerY;
self.center = center;
}
- (CGFloat)fg_right
{
return CGRectGetMaxX(self.frame);
}
- (CGFloat)fg_bottom
{
return CGRectGetMaxY(self.frame);
}
- (void)setFg_right:(CGFloat)fg_right
{
self.fg_x = fg_right - self.fg_width;
}
- (void)setFg_bottom:(CGFloat)fg_bottom
{
self.fg_y = fg_bottom - self.fg_height;
}
@end
附上 GitHub 地址:https://github.com/herojack/UIView-FGFrame
喜欢您就 star 哦!这只是一个很简单的小分类,后面会不断总结更新一些实用的分类,敬请关注!