Ios 向UISwitch添加行为
我在我的Ios 向UISwitch添加行为,ios,ios6,ios7,subclass,uiswitch,Ios,Ios6,Ios7,Subclass,Uiswitch,我在我的IOS应用程序的许多地方使用UISwitch。其中一些是stockUISwitch,一些是子类。事情发生在iOS 6和iOS 7的大小变化。所以我写了这个方法: -(void)layoutSubviews{ if ([[[UIDevice currentDevice]systemVersion]intValue]<7) { self.frame = CGRectMake(self.frame.origin.x-28, self.frame.origin.y,
IOS
应用程序的许多地方使用UISwitch
。其中一些是stockUISwitch
,一些是子类
。事情发生在iOS 6和iOS 7的大小变化。所以我写了这个方法:
-(void)layoutSubviews{
if ([[[UIDevice currentDevice]systemVersion]intValue]<7) {
self.frame = CGRectMake(self.frame.origin.x-28, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}
}
-(无效)布局子视图{
如果([[[UIDevice currentDevice]systemVersion]intValue]您只希望在调用setFrame:时更改frame属性。请尝试编写一个覆盖setFrame:的UISwitch类别:
一个类别将被所有子类继承,因为setFrame:是从UIView继承的,并且不是在UISwitch中声明的,所以您可以重写setter
也许是这样的-
// UISwitch+UISwitchAdditions.h
#import <UIKit/UIKit.h>
@interface UISwitch (UISwitchAdditions)
- (void)setFrame:(CGRect)frame;
@end
//UISwitch+UISwitch.h
#进口
@接口UISwitch(UISwitchAdditions)
-(void)setFrame:(CGRect)frame;
@结束
现在是.m
// UISwitch+UISwitchAdditions.m
#import "UISwitch+UISwitchAdditions.h"
#define X_OFFSET -28.0 // tweak your offset here
@implementation UISwitch (UISwitchAdditions)
-(void)setFrame:(CGRect)frame {
// get OS version
float osVersion = [[UIDevice currentDevice].systemVersion floatValue];
// now the conditional to determine offset
if (osVersion < 7.0) {
// offset frame before calling super
frame = CGRectOffset(frame, X_OFFSET, 0.0);
[super setFrame:frame];
}
else {
// no offset so just call super
[super setFrame:frame];
}
}
@end
//UISwitch+UISwitch.m
#导入“UISwitch+UISwitchAdditions.h”
#定义X_偏移量-28.0//在此处调整偏移量
@实现UISwitch(UISwitchAdditions)
-(void)setFrame:(CGRect)frame{
//获取操作系统版本
float osVersion=[[UIDevice currentDevice].systemVersion floatValue];
//现在是确定偏移量的条件
如果(osVersion<7.0){
//调用super之前的偏移帧
帧=CGRectOffset(帧,X_偏移,0.0);
[超级设置帧:帧];
}
否则{
//没有补偿,所以就叫超级吧
[超级设置帧:帧];
}
}
@结束
我认为@ KudoCC有一个关于LayOutSubVIEW的有效点。记住把你的类的头(在这个例子中,UISwitc+UISwitChudio.h)导入到调用SET框架的任何类中:如果你发现自己把它导入很多类,那么你可以考虑把它放在预编译的头中。
在本例中,我使用了CGRectOffset,其中您使用了CGRectMake。为什么不创建一个类,并在其中使用此方法和此类对象呢?我认为这里存在逻辑错误。每次调用layoutSubviews
时,您的帧都会更改。或者您可以确保只调用一次。