2012-04-17 30 views
11

我正在尝试创建&对于具有圆角的矩形,使用一个非常简单的UIView子类。我创建了一个新的类,如下所示:iOS - 为圆角矩形创建UIView子类

RoundedRect.h

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 

@interface RoundedRect : UIView 
@end 

RoundedRect.m

#import "RoundedRect.h" 

@implementation RoundedRect 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     [[self layer] setCornerRadius:10.0f]; 
     [[self layer] setMasksToBounds:YES]; 
    } 
    return self; 
} 
@end 

我使用的是iOS 5.1故事板,并且已经设置了自定义类财产IB检查器窗口改为'RoundedRect',但是当我运行应用程序时,矩形仍然有方角。我错过了明显的东西吗?

由于 乔纳森

回答

9

当视图是从XIB文件实例化不被调用的方法initWithFrame。而是调用初始化程序,因此您需要在此方法中执行相同的初始化。

+0

非常感谢,这是做的伎俩! – 2012-04-17 11:58:29

+0

我倾向于在'-awakeFromNib'中做额外的设置。这有什么问题吗? – d11wtq 2013-02-16 00:50:27

+1

区别在于,一旦所有对象从XIB加载完成,就会发送'awakeFromNib'。它可能会或可能不是我们想要的,我想在很多情况下根本就没有关系。 – Krumelur 2013-02-16 09:16:39

3

对于从NIB文件加载的视图,指定的初始化程序为initWithCoder:。在这种情况下不调用initWithFame:

17

的其他人已经回答了这个问题,但我会重构它这样在笔尖和代码允许使用

#import "RoundedRect.h" 

@implementation RoundedRect 

- (id)initWithFrame:(CGRect)frame; 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     [self commonInit]; 
    } 
    return self; 
} 

- (id)initWithCoder:(NSCoder *)aDecoder; 
{ 
    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     [self commonInit]; 
    } 
    return self; 
} 

- (void)commonInit; 
{ 
    CALayer *layer = self.layer; 
    layer.cornerRadius = 10.0f; 
    layer.masksToBounds = YES; 
} 

@end 
22

在iOS 5中和起来,就完全没有必要的子类 - 你可以从Interface Builder中完成。

  1. 选择您想要修改的UIView。
  2. 转到Identity Inspector。
  3. 在“用户定义的&运行时属性”中,在关键路径中添加“layer.cornerRadius”,类型应该是“Number”以及您需要的任何设置。
  4. 还要将'layer.masksToBounds'添加为布尔值。
  5. 完成!没有子类,全部在IB。
0

如果从笔尖的UIView负荷,你应该使用方法

- (void)awakeFromNib