how to code NSButton to look just like image

只谈情不闲聊 提交于 2021-01-26 19:42:31

问题


Using code (not the Interface builder) I need to create an NSButton that looks like an image. Specifically I want to use NSImageNameStopProgressFreestandingTemplate and I need it not to look like button but to look like the image. This means:
1. No 'button down' look
2. No border, no any visibility of the button

Thanks.


回答1:


I know this response is a bit late, but you could try this, given thisButton:

[thisButton setImage:[NSImage imageNamed:NSImageNameStopProgressFreestandingTemplate]];
[thisButton setImagePosition:NSImageOnly];
[thisButton setBordered:NO];

That last line is the key bit: removing the button border effectively strips it of its bezel, leaving only the image to click on. (BTW, I haven't tried the above code specifically, so you may need to throw in a couple of other tweaks, such as setting the imageScaling or buttonType, to get it to work best.)

One final note: If you're using a template image (as you said you would), Cocoa will automatically display it with a slight dark-grey gradient; when the button is clicked, it will momentarily darken to solid black. This is an automatic "'button down' look" you didn't want; however, it is very subtle, and is a good indicator that the button worked. If you don't want this to happen, you could get an instance of the desired image and [stopImage setTemplate:NO]; on it.




回答2:


If you don't want to use a templated but want the push down highlight anyways, you can also use the following setup for an NSButton:

let imageButton = NSButton()
imageButton.image = NSImage(named: "MyImage")!
imageButton.bezelStyle = .shadowlessSquare
imageButton.isBordered = false
imageButton.imagePosition = .imageOnly

The important thing to make the highlight work on any image is to set bezelStyle to shadowlessSquare.

I know this behavior wasn't requested in the question, but it might be useful for others.




回答3:


Disable isBordered

let button = NSButton(
  image: NSImage(named: NSImage.Name("plus"))!,
  target: self,
  action: #selector(onButtonPress)
)

button.isBordered = false


来源:https://stackoverflow.com/questions/4533759/how-to-code-nsbutton-to-look-just-like-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!