iOS - Create UIView subclass for rounded rectangle

穿精又带淫゛_ 提交于 2019-12-03 12:38:09

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.

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.

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

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

If UIView load from Nib, you should use method

- (void)awakeFromNib
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!