iOS設定frame的簡單方法

來源:互聯網
上載者:User

標籤:

在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.hWZLCodeLibraryCreated 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.mWZLCodeLibrary#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



iOS設定frame的簡單方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.