iOS - 为圆角矩形创建UIView子类

Jon*_*ham 11 subclass objective-c storyboard uiview ios

我正在尝试为一个带圆角的矩形创建和使用一个非常简单的UIView子类.我创建了一个新类,如下所示:

RoundedRect.h

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

@interface RoundedRect : UIView
@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我正在使用iOS 5.1和故事板,并在IB检查器窗口中将自定义类属性设置为'RoundedRect',但是当我运行应用程序时,矩形仍然有方角.我错过了一些明显的事吗?

谢谢乔纳森

And*_*sky 23

在iOS 5及更高版本中,绝对不需要子类 - 您可以从Interface Builder完成所有操作.

  1. 选择要修改的UIView.
  2. 转到Identity Inspector.
  3. 在"用户定义和运行时属性"中,在"密钥路径"中添加"layer.cornerRadius","类型"应为"数字"以及您需要的任何设置.
  4. 还要将'layer.masksToBounds'添加为布尔值.
  5. 完成!没有子类化,全部都在IB中.


Pau*_*l.s 18

其他人已经回答了这个问题,但我会像这样重构它,以便在nib和代码中使用

#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
Run Code Online (Sandbox Code Playgroud)


Kru*_*lur 10

initWithFrame从XIB文件实例化视图时,不会调用该方法.而是initWithCoder:调用初始化程序,因此您需要在此方法中执行相同的初始化.