如何为子视图添加活力效果?

How can I add a vibrancy effect to a subview?

下面的代码适用于简单的:

UIVisualEffectView *blurView

但是,当我尝试给它添加一个具有活力效果的标签时,它因眼泪和错误而崩溃。 :(

    UIBlurEffect * effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

    _blurView = [[UIVisualEffectView alloc] initWithEffect:effect];
    _blurView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.5];
    [self addSubview:_blurView];

    UIVisualEffectView * vibrancyView = [[UIVisualEffectView alloc] initWithEffect:effect];

    [_blurView.contentView addSubview:vibrancyView];

    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont boldSystemFontOfSize:17.0];
    _titleLabel.textColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    _titleLabel.text = @"TITLE";

    [vibrancyView.contentView addSubview:_titleLabel];

自定义设置框的方法:

#pragma mark -

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    _blurView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);

    _titleLabel.frame = CGRectMake(16, 16, 200, 30);
}

标签没有显示在屏幕上,但如果我将它作为简单的子视图添加到 blurView,它就会显示。

[_blurView addSubview:_titleLabel];

我正在使用初始化方法中的代码,这可能是问题的原因吗?

- (instancetype)init
{
    self = [super init];

    if (self) {

        // Code...
    }

    return self;
}

我需要它在初始化方法中,以便与我编写代码的方式保持一致。

Source

编辑 1:

vibrancyView 也应该设置其框架。

vibrancyView.frame = CGRectMake(0, 0, _blurView.frame.size.width, _blurView.frame.size.height);

原来源代码中的例子是不完整

编辑 2:

标签确实出现了,但没有活力效果。

求助!

您缺少活力效果的创建:

UIVibrancyEffect * vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:effect];

稍后您应该将其传递给活力视图:

UIVisualEffectView * vibrancyView = [[UIVisualEffectView alloc] initWithEffect: vibrancyEffect];


我已经在 github 上提供了 class,它简化了创建 UIVisualEffectView 所需的所有锅炉代码。