在NSButton中定位一个NSImage

问题描述:

我有一个编程创建的NSButton。在所述按钮中,我有一个NSImage作为图标:在NSButton中定位一个NSImage

let button = NSButton(frame: NSRect(x: 10, y: (200 + (50 * id)), width: 100, height: 50)) 
button.action = #selector(self.switchToView) 
let img = NSImage(named: "wob_icon") 
button.image = img 

我想要做的是得到图像10pt。从按钮的左侧,垂直居中。到目前为止,图像在水平方向和垂直方向都显示为中心,但由于看起来并不像我能够定义一个框架或类似的东西,所以我无法真正移动它。

有没有办法在其父(按钮)内移动图像?

谢谢。

也许你可以在NSButton上使用imagePosition属性? (documented here)。

它使用NSCellImagePositiondocumented here)类型的枚举,并允许您将图像设置为文本左侧,文本右侧,文本上方,文本下方等。

你仍然没有机会将事物像素完美对齐,但如果你可以忍受这种情况,那么imagePosition似乎是要走的路。

这里是如何使用它:

let button = NSButton(frame: NSRect(x: 10, y: 10, width: 100, height: 50)) 
button.action = #selector(self.switchToView) 
let img = NSImage(named: "wob_icon") 
button.image = img 
button.imagePosition = .imageLeft 
button.title = "Look left :)" 

这一点让我这个惊人的UI:

button with image 希望帮助你。