带圆角的UIView:我忘记了什么

时间:2012-12-27 11:08:38

标签: ios quartz-graphics

我正在使用最新的SDK开发iOS应用程序。

我有这个自定义UIView:

#define ANNOTATION_WIDTH 250
#define ANNOTATION_HEIGHT 200

@implementation CustomView

- (id)initwithTitle:(NSString* )title subTitle:(NSString* )subTitle
{
    CGRect annotationFrame =
    CGRectMake(10, 10, ANNOTATION_WIDTH, ANNOTATION_HEIGHT);

    if ([self initWithFrame:annotationFrame])
    {
        self.backgroundColor = [UIColor redColor];
        self.opaque = YES;
        /*
        UILabel* nameLabel =
        [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ANNOTATION_WIDTH, 20.0)];

        nameLabel.backgroundColor = [UIColor whiteColor];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        //nameLabel.text = coordinate.name;
        nameLabel.text = title;
        [nameLabel sizeToFit];
        [nameLabel setFrame: CGRectMake(0,
                                        0,
                                        nameLabel.bounds.size.width + 8.0,
                                        nameLabel.bounds.size.height + 8.0)];
        [self addSubview:nameLabel];

        UILabel* placeLabel =
        [[UILabel alloc] initWithFrame:CGRectMake(25, 0, ANNOTATION_WIDTH, 20.0)];

        placeLabel.backgroundColor = [UIColor whiteColor];
        placeLabel.textAlignment = NSTextAlignmentCenter;
        //placeLabel.text = coordinate.place;
        placeLabel.text = subTitle;
        [placeLabel sizeToFit];
        [placeLabel setFrame:CGRectMake(25,
                                        0,
                                        placeLabel.bounds.size.width + 8.0,
                                        placeLabel.bounds.size.height + 8.0)];
        [self addSubview:placeLabel];
        */
    }

    return self;
}

我将展示一个标题和一个副标题,但现在该代码是评论,因为我正在测试一些东西。

要将此自定义视图添加到UIViewController,请执行以下操作:

#import "ViewController.h"
#import "CustomView.h"
#import <QuartzCore/QuartzCore.h>

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    CustomView* cView = [[CustomView alloc] initwithTitle:@"Titulo" subTitle:@"Subtitulo"];
    cView.layer.cornerRadius = 10;
    cView.layer.masksToBounds = YES;

    [self.view addSubview:cView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

如果我没有显示标题和subTitle而且我没有看到我的customView,但是我显示了标题和subTitle我只看到圆角的左上角。

我也试过这个,但它不起作用:

CustomView* cView = [[CustomView alloc] initwithTitle:@"Titulo" subTitle:@"Subtitulo"];
cView.layer.cornerRadius = 10;
cView.clipsToBounds = YES;

有没有办法在不添加任何子视图的情况下显示带圆角的UIView?

我不知道它发生了什么,我不知道为什么我只是左上角。

2 个答案:

答案 0 :(得分:0)

你试过这个

吗?
[self.layer setCornerRadius:10];
[self.layer setMasksToBounds:YES];

答案 1 :(得分:0)

试试这个:

cView.layer.cornerRadius = 10.0f;
cView.layer.masksToBounds = YES;
cView.layer.opaque = NO;
[self.view addSubview:cView];