【问题标题】:Add behaviour to UISwitch向 UISwitch 添加行为
【发布时间】:2013-12-26 09:17:51
【问题描述】:

我在我的IOS 应用程序的许多地方都使用UISwitch。其中一些是股票UISwitch,其中一些是subclassed。问题在于iOS 6 VS 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);
    }
}

我可以更改每个子类并添加此方法,但我认为这不是正确的方法。 如何设置此类以影响基础 UISwitch 类?

【问题讨论】:

  • 为什么不创建一个类并在其中放置这个方法并使用这个类对象
  • 我认为这里存在逻辑错误。每次layoutSubviews 被调用时,你的框架都会改变。或者你可以确保它只被调用一次。

标签: ios ios6 ios7 subclass uiswitch


【解决方案1】:

您只希望在调用 setFrame: 时更改 frame 属性。尝试编写一个覆盖 setFrame 的 UISwitch 类别: 一个category会被所有子类继承,因为setFrame:继承自UIView,并且没有在UISwitch中声明,所以可以重写setter。

可能是这样的-

// UISwitch+UISwitchAdditions.h
#import <UIKit/UIKit.h>

@interface UISwitch (UISwitchAdditions)

- (void)setFrame:(CGRect)frame;

@end

现在是 .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

我认为@KudoCC 关于 layoutSubviews 的观点是正确的。请记住将您的类别的标题(在此示例中为 UISwitch+UISwitchAdditions.h)导入任何将调用 setFrame 的类:如果您发现自己将其导入到很多类中,那么您可以考虑放置它而是在您的预编译头文件中。 在您使用 CGRectMake 的示例中,我使用了 CGRectOffset。

【讨论】:

    猜你喜欢
    • 2013-04-04
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多