我无法在xcode 9.1中的UIButton上显示图像

时间:2017-10-04 00:26:58

标签: ios swift xcode uibutton

这是我的代码。我想在三个按钮中显示三个随机食物图像。我检查语法,看起来也不错。我不确定图像。我在图像集中有1x,2x和3x图像。

import UIKit
import GameplayKit

class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!

    @IBOutlet weak var button2: UIButton!

    @IBOutlet weak var button3: UIButton!


    var foodItems = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //Add food items into Array

        foodItems.append("Apple")
        foodItems.append("Banana")
        foodItems.append("Bhindi")
        foodItems.append("Bread")
        foodItems.append("CornFlakes")
        foodItems.append("Dal Dhokli")
        foodItems.append("Egg")
        foodItems.append("Milk")
        foodItems.append("Nan")
        foodItems.append("Roti")

        // Add border to button(default color is black)

        button1.layer.borderWidth = 1
        button2.layer.borderWidth = 1
        button3.layer.borderWidth = 1

        // change border color to gray


        button1.layer.borderColor = UIColor.gray.cgColor
        button2.layer.borderColor = UIColor.gray.cgColor
        button3.layer.borderColor = UIColor.gray.cgColor

        // Do any additional setup after loading the view, typically from a nib.

        askQuestion()
    }
    // ask question to identify foodItem

    func askQuestion() {
        foodItems = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: foodItems) as! [String]
        //set image to button 1, 2 and 3

        button1.setImage(UIImage(named: foodItems[0]), for: .normal)
        button2.setImage(UIImage(named: foodItems[1]), for: .normal)
        button3.setImage(UIImage(named: foodItems[2]), for: .normal)

    }

这是模拟器视图。我只能看到蓝色方块。我在图像集中有1x,2x和3x图像。

1

3 个答案:

答案 0 :(得分:1)

转到图片资源 - >选择图片 - >属性检查器 - >渲染为(在图像集中)应为默认值

please see attachment

答案 1 :(得分:1)

在xode 9拖放不起作用。您必须添加以下屏幕截图的文件。 enter image description here

enter image description here

然后使用相同的代码。

或在Assets.xcassets中添加图片

答案 2 :(得分:1)

在故事板或笔尖中将按钮类型更改为自定义

enter image description here