Question

I'm trying to create an NSButton with a custom background using the technique found here: http://youtu.be/7MZJxPOo_xU. Everything worked fine for me except the part at the end where he explains how to use self.layer.contentscenter to make sure the edges of the image don't stretch in the wrong way. I tried to implement it in the same way, but it doesn't do anything for me, and nothing changes when I comment it out. Am I implementing something wrong or just misunderstanding what's going on here? Here's my code and images of the problem.

How the button looks when square (as designed):

enter image description here

How it looks when stretched: (notice how the top and bottom edges compress vertically, when they should only stretch horizontally)

enter image description here

CustomButton.m

@implementation CustomButton

- (BOOL)wantsUpdateLayer{
    return YES;
}

- (void)updateLayer{
    self.layer.contentsCenter = CGRectMake(0.5, 0.5, 0, 0);

    if (self.state == NSOnState) {
        self.layer.contents = [NSImage imageNamed:@"buttonPressedAndSelected.png"];
    }
    else if (self.state == NSOffState){
        self.layer.contents = [NSImage imageNamed:@"buttonSelected.png"];
    }
}

@end
Was it helpful?

Solution

Your image is too large for the button. The problem is that it has to start compressing the tops and bottoms because the button has been squished smaller than the actual artwork. Try making that artwork for the square much smaller (at least as small as the button will be).

I have found that there is an issue with my method of doing this though on Mavericks and it doesn't want me to change the contentsCenter of the layer. However, it should still work.

Btw, thanks for watching the tutorial :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top