几句代码搞定计算每个控件的frame

程序员们都在因为计算每个控件的frame发愁, 因为控件frame是一个结构体类型, 不能直接进行修改, 需要..., 所以这里问我为大家写了一个类, 直接创建一个类, 进行拷贝就可以使用

  • 这种方法的头文件最好写到pch 文件中, 因为pch 文件中, 因为这种计算控件的frame太常用了
  • 这里对CGPoint几种不常用的点没有定义

  • 创建一个UIVeiw+Extension的分类
  • 在.h文件中需要定义属性
  • 注意点: 在分类中定义的属性, 是不会生成带下划线的成员变量的
#import <UIKit/UIKit.h>

@interface UIView (Extension)

@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@property (nonatomic, assign) CGSize size;

@end
  • 在.m文件中重写属性的getter 和setter方法, 对属性的frame进行修改
#import "UIView+Extension.h"

@implementation UIView (Extension)

-(void)setCenterX:(CGFloat)centerX {
    
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

-(CGFloat)centerX {
    return self.center.x;
}

-(void)setCenterY:(CGFloat)centerY {
    
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

-(CGFloat)centerY {
    return self.center.y;
}


-(void)setX:(CGFloat)x {

    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

-(void)setY:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

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

-(CGFloat)y {

    return self.frame.origin.y;
}

-(void)setWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

-(void)setHeight:(CGFloat)height{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

-(CGFloat)width {

    return self.frame.size.width;
}

-(CGFloat)height {

    return self.frame.size.height;
}

-(void)setSize:(CGSize)size {
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
    
}

-(CGSize)size {

    return self.frame.size;
}
@end

请各位小伙伴多提意见

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,565评论 25 709
  • 1、窗体 1、常用属性 (1)Name属性:用来获取或设置窗体的名称,在应用程序中可通过Name属性来引用窗体。 ...
    Moment__格调阅读 10,051评论 0 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,448评论 19 139
  • 自工作之后,午睡基本就被剥夺了,导致下午大脑会不断崩溃。戳大腿的方法太过暴力,已然被淘汰。七窍刺激是更可行的方案。...
    snipersteve阅读 3,652评论 1 3
  • 真的好身体才是实现梦想的基础 一:公交英语《开悟英语》每次拿起这本书最想最感谢恰恰! 二:地铁看书《巨婴国》 三:...
    悦洋行者阅读 2,405评论 0 0