【问题标题】:How to implement image button on OSX in RubyMotion?如何在 RubyMotion 中的 OSX 上实现图像按钮?
【发布时间】:2015-02-18 03:24:11
【问题描述】:

这让我觉得这应该非常简单,但我就是无法让它发挥作用。

我正在创建一个这样的按钮:

closeButton = NSButton.alloc.initWithFrame(
    [[10, 10], [100, 22]]
  ).tap do |button|
    button.bezelStyle = NSShadowlessSquareBezelStyle
    button.buttonType = NSMomentaryChangeButton
    button.title = 'Close'
    button.bordered = false
    button.image = NSImage.imageNamed('img/circle')
    p button.image
    button.imagePosition = NSImageOnly
    button.target = window
    button.action = 'close'
  end

有2张图片,circle.pngcircle@2x.png,存储在/Resources/img中。

不用说,我得到一个灰色按钮,里面没有文字或图像。此外,p button.image 返回nil

我已经多次清理和重建我的项目。

这似乎不应该那么难以实现。我忽略了什么?

【问题讨论】:

    标签: objective-c ruby macos cocoa rubymotion


    【解决方案1】:

    首先,让我说我对 OSX 的经验为零,但我希望这些 iOS 信息会有所帮助。我被告知它们非常相似。您需要确保您使用的是自定义按钮 (UIButtonTypeCustom)。这将允许您使用背景图像功能。

    这里有一些很好的示例代码,可能会对您有所帮助。

    https://github.com/IconoclastLabs/rubymotion_cookbook/tree/master/ch_2/16_buttons

    再次,如果这不起作用,我很抱歉,但我想我会发布此信息以提供帮助!

    【讨论】:

    • 感谢您的回复!遗憾的是,OSX API 中似乎不存在 UIButtonTypeCustom。不过,请欣赏它。
    【解决方案2】:

    所以我有点想通了。看起来imageNamed 没有按我预期的方式工作,或者我只是使用不正确。

    我可以通过执行以下操作在按钮上设置图像:

    NSButton.alloc.initWithFrame(
        [[110, 10], [100, 22]]
    ).tap do |button|
        neutralImgPath = NSBundle.mainBundle.pathForResource("img/circle2", ofType: "png")
        neutralImgUrl = NSURL.fileURLWithPath(neutralImgPath)
        neutralImg = NSImage.alloc.initWithContentsOfURL(neutralImgUrl)
    
        button.setImage(neutralImg)
    
        button.setImageScaling(NSImageScaleProportionallyDown)
        button.setImagePosition(NSImageOnly)
    
        button.translatesAutoresizingMaskIntoConstraints = false
        button.bordered = false
        button.bezelStyle = NSShadowlessSquareBezelStyle
        button.buttonType = NSMomentaryChangeButton
    
        button.target = MainAppWindow.get
        button.action = 'minimize:'
    end
    

    肯定很想找到一种更简洁的方法来做到这一点,但现在,它完成了工作!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      相关资源
      最近更新 更多