1. 程式人生 > >IOS 雜筆-12(類別de巧用 有便於Frame的操作)

IOS 雜筆-12(類別de巧用 有便於Frame的操作)

獲取 setw right property elf ext src gin idt

在實際開發中很多時候我們都為了控件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
技術分享

復制粘貼即可使用,也可以改變為其他控價。

IOS 雜筆-12(類別de巧用 有便於Frame的操作)