iOS学习之路 ios零碎记录

UIView扩展

2016-02-23  本文已影响320人  南方_H

算是一个小工具,可以提升大家以后的码速!
效果如下:

self.view.frame.size.width
//直接写成
self.width

我们只需要做一个UIView的扩展

UIView+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) CGSize  size;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY; 
@end

UIView+Extension.m

#import "UIView+Extension.h"

@implementation UIView (Extension)

- (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)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;
}

- (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;
}

- (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

好了,我们用一下看下效果:


- (void)layoutSubviews {
//    [super layoutSubviews];
    
    // 设置按钮的frame
    int btnCount = (int)self.btnArray.count;
    CGFloat btnW = self.width / btnCount;
    CGFloat btnH = self.height;
    for (int i = 0; i < btnCount; i++){
        UIButton *btn = self.btnArray[i];
        btn.width = btnW;
        btn.height = btnH;
        btn.y = 0;
        btn.x = i *btnW;
    }
    
    int divideCount = (int)self.lineArray.count;
    for (int i = 0; i < divideCount; i++){
        UIImageView *divide = self.lineArray[i];
        divide.width = 1;
        divide.height = btnH;
        divide.centerX = (i + 1) *btnW;
        divide.centerY = btnH * 0.5;
    }
}

是不是方便多了呀!童鞋们,直接将代码复制到UIView的扩展中就行了!!

上一篇下一篇

猜你喜欢

热点阅读