【问题标题】:Why doesn't my IBDesignable allow me to use setImage: on my custom UIButton?为什么我的 IBDesignable 不允许我在自定义 UIButton 上使用 setImage:?
【发布时间】:2014-12-23 02:03:03
【问题描述】:

layoutSubviews 中,我调用setImage() 并将UIImage 传递给它,但它从未出现在Interface Builder 中,但它总是在我运行程序时出现。

【问题讨论】:

    标签: ios xcode uiview ios8 ibdesignable


    【解决方案1】:

    您可能正在使用此方法加载 UIImage:

    UIImage *image = [UIImage imageNamed:@"image"];
    

    这在界面生成器中不起作用,因为 imageNamed: 方法使用主包,但 IB 以不同的方式加载资源。试试这样的:

    - (void)prepareForInterfaceBuilder
    {
        UIImage *image = [UIImage imageNamed:@"image" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
        [self setImage:image forState:UIControlStateNormal];
    }
    

    【讨论】:

      【解决方案2】:

      将为像我一样遇到此问题的任何人提供快速答案。

      问题在于 Interface Builder 中的图像路径与您的应用程序中的路径不同。

       let bundle = Bundle(for: self.classForCoder)
       image = UIImage(named: "your_image.png", in: bundle, compatibleWith: self.traitCollection)!
       self.setImage(image, for: .normal) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 2020-10-30
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多