扩展(extension)
扩展是向一个已有的类、结构体或枚举类型添加新的功能。在swift中扩展是没有名字的,但在Objective-C中Category是有名字的,而且只能扩展类(类别)
例如在OC中我们想直接拿到某个view的frame并修改,只需要新建一个UIView+Frame的Category
//UIView+Frame.h
#import <UIKit/UIKit.h>
@interface UIView (Frame)
@property (nonatomic ,assign) CGFloat width;
@property (nonatomic ,assign) CGFloat height;
@property (nonatomic ,assign) CGFloat x;
@property (nonatomic ,assign) CGFloat y;
@property (nonatomic ,assign) CGFloat centerX;
@property (nonatomic ,assign) CGFloat centerY;
//UIView+Frame.m
#import "UIView+Frame.h"
@implementation UIView (Frame)
- (void)setCenterX:(CGFloat)centerX{
CGPoint center = self.center;
center.x = centerX;
self.center = center;
}
- (void)setCenterY:(CGFloat)centerY{
CGPoint center = self.center;
center.y = centerY;
self.center = center;
}
- (CGFloat)centerX{
return self.center.x;
}
- (CGFloat)centerY{
return self.center.y;
}
- (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.bounds.size.width;
}
- (CGFloat)height{
return self.bounds.size.height;
}
- (CGFloat)x{
return self.frame.origin.x;
}
- (CGFloat)y{
return self.frame.origin.y;
}
就可以在项目中丝滑的使用
//MyProjectViewController.m
NSUInteger index = self.scrollView.contentOffset.x / self.scrollView.width;
UIViewController *childVC = self.childViewControllers[index];
childVC.view.y = 0;
childVC.view.x = self.scrollView.contentOffset.x;
childVC.view.width = self.scrollView.width;
childVC.view.height = self.scrollView.height;
而在swift中,如果不进行"扩展",我们只能这么写:
//MyProjectViewController.swift
let index = Int(self.scrollView.contentOffset.x / self.scrollView.frame.width)
var childVC = self.childViewControllers[index]
childVC.view.frame = CGRect(x: self.scrollView.contentOffset.x, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height)
self.scrollView.addSubview(childVC.view)
要添加UIView的分类,只需要新建一个swift文件
//UIView+Frame.swift
import UIKit
extension UIView {
var width : CGFloat {
get{
return self.bounds.size.width
}
set(width) {
//var frame = self.frame
//frame.size.width = width
//self.frame = frame
self.frame.size = CGSize(width: width, height: self.frame.height)
}
}
}
即可以在项目中使用了:
//MyProjectViewController.swift
let index = Int(self.scrollView.contentOffset.x / self.scrollView.frame.width)
var childVC = self.childViewControllers[index]
childVC.view.x......
childVC.view.y......
childVC.view.width = self.scrollView.width
childVC.view.height......
self.scrollView.addSubview(childVC.view)
网友评论