macOS 10.12.4 NSButton After adding CAGradientLayer, button title is not displayed

The purpose of the following code is to achieve a gradient background color In newer versions, it looks fine, but in macOS 10.12.4, the title of the button doesn't appear

- (void)setGradient:(NSArray<__kindof NSColor *> *)colorArr StartPoint:(CGPoint)startPoint EndPoint:(CGPoint)endPoint {
    self.wantsLayer = YES;
    CAGradientLayer *gradinentlayer = [CAGradientLayer layer];
    NSMutableArray *array = [NSMutableArray array];
    for (NSColor *color in colorArr) {
        [array addObject:(id)color.CGColor];
    }
    gradinentlayer.colors = array;
    gradinentlayer.startPoint = startPoint;
    gradinentlayer.endPoint = endPoint;
    gradinentlayer.frame = self.bounds;
    [self.layer insertSublayer:gradinentlayer atIndex:0];
}

How do I make the title text appear, other than adding a subview? Any help would be appreciated!

  • Maybe because you're hiding the label by placing the new layer at index 0. Find the Label layer index and insert the gradient beneath it.

  • @MobileTen I get the following output by iterating through the layers in different versions On macOS 10.12.4, the output is: (

      "<CAGradientLayer: 0x60800002ff00>" ) On macOS 12.4, the output is: (   "<CAGradientLayer: 0x6000003d05c0>",   "<NSTextLayer: 0x600000d0ddd0>" ) Therefore, I suspect that the title does not exist as a layer in macOS10.12.4

Add a Comment

Replies

@MobileTen I get the following output by iterating through the layers in different versions On macOS 10.12.4, the output is: (

    "<CAGradientLayer: 0x60800002ff00>"

) On macOS 12.4, the output is: (

    "<CAGradientLayer: 0x6000003d05c0>",

    "<NSTextLayer: 0x600000d0ddd0>"

)

Therefore, I suspect that the title does not exist as a layer in macOS10.12.4