在iOS中view的frame屬性使用地太頻繁了,尤爲是調UI的時候。咱們知道,正常狀況下咱們沒法對frame的某個屬性(x,y,width,height等)進行單獨修改,好比: someView.frame.x = 100; 這種方式是不容許的,但實際上咱們更常常遇到的是frame的大部分元素值保持不變,只改變其中的一部分。相信這個煩惱困擾了很多人,因而咱們不得不用如下兩種方法去達到目的: 法1: CGRect frame = someView.frame; frame.x =100; frame.width = 200; someView.frame = frame; 法2: someView.frame = CGRectMake(100, XXX, 200, XXX); 法2看起來也很精簡,但實際上也很麻煩,由於實際應用場景中x, y, width, height四個值都是依賴別的變量,致使法2的語句很是長。簡而言之,以上方法都不夠「優雅」。那怎樣纔算優雅呢?我以爲若是咱們能以下這樣直接修改某個值就完美了: someView.x = 100; someView.width = 200; 咱們跳過someView的frame屬性,直接修改了咱們想要的元素值。幸運的是,咱們使用category能夠至關方便地達到目的,這是一件一勞永逸的事情,引入一次category後整個工程均可以使用這種修改方法: UIView+Frame.h WZLCodeLibrary Created by wzl on 15/3/23. Copyright (c) 2015年 Weng-Zilin. All rights reserved. #import <UIKit/UIKit.h> @interface UIView (Frame) @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @property (nonatomic, assign) CGPoint origin; @property (nonatomic, assign) CGSize size; @end UIView+Frame.m WZLCodeLibrary #import "UIView+Frame.h" @implementation UIView (Frame) - (void)setX:(CGFloat)x { CGRect frame = self.frame; frame.origin.x = x; self.frame = frame; } - (CGFloat)x { return self.frame.origin.x; } - (void)setY:(CGFloat)y { CGRect frame = self.frame; frame.origin.y = y; self.frame = frame; } - (CGFloat)y { return self.frame.origin.y; } - (void)setOrigin:(CGPoint)origin { CGRect frame = self.frame; frame.origin = origin; self.frame = frame; } - (CGPoint)origin { return self.frame.origin; } - (void)setWidth:(CGFloat)width { CGRect frame = self.frame; frame.size.width = width; self.frame = frame; } - (CGFloat)width { return self.frame.size.width; } - (void)setHeight:(CGFloat)height { CGRect frame = self.frame; frame.size.height = height; self.frame = frame; } - (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