【问题标题】:unable to setImage to UIButton in Xamarin C#无法在 Xamarin C# 中将图像设置为 UIButton
【发布时间】:2014-07-29 05:52:32
【问题描述】:

无法为setImageUIButton。

当使用 Image 设置 backgroundColor 时,我想将其设置为“backButton.png”

当 setImage 为 UIButton 时,它根本不显示

 backButton.SetImage (UIImage.FromFile ("/Images/backButton.png"), UIControlState.Normal);

我想将图片设置为UIButton。

//下面是代码

UIButton backButton = UIButton.FromType(UIButtonType.Custom);
backButton.Frame = new RectangleF (5, 5, 45, 30);
backButton.BackgroundColor =  UIColor.FromPatternImage (UIImage.FromBundle ("/Images/backButton.png"));
backButton.SetImage (UIImage.FromFile ("/Images/backButton.png"), UIControlState.Normal);
backButton.TouchUpInside += (sender, ea) => {
    this.NavigationController.PopViewControllerAnimated(true);
};

【问题讨论】:

  • 您确定要指定/Images/ 文件夹吗?我认为如果您从捆绑包中挑选,则没有文件夹结构,所有文件都位于同一目录中
  • 你说得对...谢谢!

标签: c# ios iphone uibutton xamarin


【解决方案1】:

我对@9​​87654323@ 了解不多。但是 xcode 项目中呈现的目录结构与实际不同(应用编译后)。
所有文件和资源都位于名为main bundle 的同一目录中。
要访问您的资源,您只需从主包中请求它。您不必指定 xcode 项目导航器的目录(资源所在的目录)。

你可以阅读更多directory structure here

【讨论】:

    【解决方案2】:

    这是因为当您通过属性框从 Visual Studio 设置图像时,它会设置图像路径,如 images\image1.png [当 image1.png 文件位于 \Resources\Images 文件夹中时。

    但 MAC 不支持“\”路径,您需要提供带有“/”的路径。

    【讨论】:

      【解决方案3】:

      我最近遇到了这个问题。我读到 Apple 最近强制执行了一项更改,即当您在 Xamarin 中创建项目时,所有资源都必须驻留在 Resources 目录中。您可以在 Resources 目录中创建 Image 目录并将您的图像放在那里。

      现在读取它们很简单 - 如果图像在资源目录中,您可以使用

      UIImage.FromFile ("backButton.png")
      

      但是,如果您的图片在 Resources/Images 中,那么只需使用

      UIImage.FromFile ("Images/backButton.png")
      

      请注意现在位于 Resources 目录中的 Images 目录之前没有反斜杠。

      这对我有用。抱歉,我不记得告诉我仅在目录中更改和存储资源的链接,但这解决了我所有与资源相关的问题。

      【讨论】:

        【解决方案4】:

        在您发布的代码中:

        backButton.BackgroundColor =  UIColor.FromPatternImage (UIImage.FromBundle("/Images/backButton.png"));
        backButton.SetImage (UIImage.FromFile ("/Images/backButton.png"), UIControlState.Normal);
        

        您在一行中使用UIImage.FromFile,在另一行中使用UIImage.FromBundle。如果我理解您纠正了"FromBundle" 版本的工作原理,那么请尝试将这个版本也用于SetImage。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-14
          • 2022-12-01
          • 2016-04-11
          • 2010-11-30
          • 2019-04-27
          • 2017-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多