iOS - Create UIView subclass for rounded rectangle

2020-06-12 04:35发布

I'm trying to create & use a very simple UIView subclass for a rectangle with rounded corners. I've created a new class as follows :

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

I'm using iOS 5.1 with storyboards and have set the custom class property in the IB inspector window to 'RoundedRect', but when I run the app the rectangle still has square corners. Have I missed something obvious?

Thanks Jonathan

5条回答
一纸荒年 Trace。
2楼-- · 2020-06-12 05:15

The other guys have already answered the question but I would refactor it like this to enable use in nibs and in code

#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
查看更多
欢心
3楼-- · 2020-06-12 05:18

If UIView load from Nib, you should use method

- (void)awakeFromNib
查看更多
别忘想泡老子
4楼-- · 2020-06-12 05:23

In iOS 5 and up, there is absolutely no need to subclass - you can do it all from Interface Builder.

  1. Select the UIView you want to modify.
  2. Go to the Identity Inspector.
  3. In "User Defined & Runtime Attributes", add "layer.cornerRadius" in Key Path, Type should be "Number" and whatever setting you require.
  4. Also add 'layer.masksToBounds' as Boolean.
  5. Done! With no subclassing, and all in IB.
查看更多
我命由我不由天
5楼-- · 2020-06-12 05:35

The initWithFrame method is not called when the view is instantiated from a XIB file. Instead, the initWithCoder: initializer is called, so you need to perform the same initialization in this method.

查看更多
狗以群分
6楼-- · 2020-06-12 05:39

For views that are loaded from a NIB file, the designated initializer is initWithCoder:. initWithFame: is not called in this case.

查看更多
登录 后发表回答