IOS 杂笔-12(类别de巧用 有便于Frame的操作)

来源:互联网 发布:我爱发明 知乎 编辑:程序博客网 时间:2024/05/28 23:10

在实际开发中很多时候我们都为了控件frame的操作焦头烂额。

例如:我们只想要获取view的width。

我们可以这么操作:view.frame.size.width

有时我们想要改变view的width然而我们不能直接改变->需要三部曲。

让人抓狂,为了解决这里烦恼我们可以通过改变类别来达到理想的效果。

下面是类别的.h文件:

复制代码
////  UIView+CXExtension.h//////  Created by ma c on 16/3/25.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import <UIKit/UIKit.h>@interface UIView (CXExtension)@property (nonatomic, assign) CGSize size;@property (nonatomic, assign) CGFloat width;@property (nonatomic, assign) CGFloat height;@property (nonatomic, assign) CGFloat x;@property (nonatomic, assign) CGFloat y;@end
复制代码

接下来是.m文件

复制代码
////  UIView+CXExtension.m//////  Created by ma c on 16/3/25.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "UIView+CXExtension.h"@implementation UIView (CXExtension)- (void)setSize:(CGSize)size{    CGRect frame = self.frame;    frame.size = size;    self.frame = frame;}- (CGSize)size{    return self.frame.size;}- (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;}- (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)width{    return self.frame.size.width;}- (CGFloat)height{    return self.frame.size.height;}- (CGFloat)x{    return self.frame.origin.x;}- (CGFloat)y{    return self.frame.origin.y;}@end
复制代码

复制粘贴即可使用,也可以改变为其他控价。

原创粉丝点击