Search code examples
iosobjective-cuilabelios-app-extensionuivibrancyeffect

Apply UIVibrancyEffect to UILabel in UITableViewCell


My Notification Center widget contains a UITableView and there is a UILabel on the UITableViewCell that I would like to 'blur'/ apply the UIVibrancyEffect to. Here is what I have tried but It seems to be causing an exception:

UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIVibrancyEffect notificationCenterVibrancyEffect]];
effectView.frame = cell.longStatusLabel.bounds;
__strong UILabel *longStatus = cell.longStatusLabel;
cell.longStatusLabel = effectView;
[effectView.contentView addSubview:longStatus];
[cell addSubview:effectView];

When I run this code my Notification Center Extension says it cannot load.


Solution

  • I think the problem is you're setting the label equal to the UIVisualEffectView. Try this instead. Create the UILabel programmatically:

    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIVibrancyEffect notificationCenterVibrancyEffect]];
    effectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    UILabel *label = [[UILabel alloc] init];
    label.text = @"my label";
    label.textColor = [UIColor colorWithWhite:1.0 alpha:0.5f];
    label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //...
    [effectView.contentView addSubview:label];
    [cell.contentView addSubview:effectView];
    

    You should also be able to do this in Interface Builder using Visual Effect Views with Blur and Vibrancy effect, it doesn't have to be done programmatically.

    Also, try setting a breakpoint when debugging if it's not working as you expect. If it refuses to load, try removing the extension from Notification Center and adding it again, or picking a different device if you're using the iOS Simulator.