ios – 如何在Swift / Xcode中为按钮设置图像

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift / Xcode中为按钮设置图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试以编程方式设置按钮的图像时,我收到“nil”错误.我究竟做错了什么?这些都不是可选项.
@IBOutlet weak var scrollView: UIScrollView!

var imageButton: UIButton!
var index: Int = 0

var images: [UIImage] = [UIImage(named: "image1.png")!,UIImage(named: "image2.png")!,UIImage(named: "image3.png")!,UIImage(named: "image4.png")!,UIImage(named: "image5.png")!,UIImage(named: "image6.png")!,UIImage(named: "image7.png")!,UIImage(named: "image8.png")!,UIImage(named: "image9.png")!,UIImage(named: "image10.png")!,UIImage(named: "image11.png")!,UIImage(named: "image12.png")!,UIImage(named: "image13.png")!,UIImage(named: "image14.png")!,UIImage(named: "image15.png")!,UIImage(named: "image16.png")!,UIImage(named: "image17.png")!,UIImage(named: "image18.png")!,UIImage(named: "image19.png")!,UIImage(named: "image20.png")!,UIImage(named: "image21.png")!,UIImage(named: "image22.png")!,UIImage(named: "image23.png")!,UIImage(named: "image24.png")!,UIImage(named: "image25.png")!,UIImage(named: "image26.png")!,UIImage(named: "image27.png")!,UIImage(named: "image28.png")!,UIImage(named: "image29.png")!,UIImage(named: "image30.png")!]


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view,typically from a nib.

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width
    //let screenHeight = screenSize.height

    let numWidth: CGFloat = 3
    let numHeight: CGFloat = 10
    self.scrollView.frame.size.width = screenWidth
    let width: CGFloat = (self.scrollView.frame.size.width - (numWidth + 1))/3

    for var i:CGFloat = 0; i < 3; ++i{
        for var j:CGFloat = 0; j < 10; ++j {

            let image: UIImage = images[index] as UIImage!


            imageButton.setImage(image,forState:UIControlState.Normal)
            imageButton.frame = CGRectMake(width*i,width*j,width,width)
            self.scrollView.addSubview(imageButton)

            index++
        }
    }
    scrollView.contentSize.height = (width)*numHeight

解决方法

我想你是再次从Image创建Image.

就这样吧

imageButton.setImage(images[index],forState:UIControlState.Normal)

希望它会奏效.

或者你可以这样做:

var images = [String]?

在viewDidLoad中

images = ["image1.png","image2.png"]
let img : UIImage = UIImage(named: images[index])!
imageButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100,100,100)//Set your own frame
imageButton.setImage(img,forState:UIControlState.Normal)

并检查它必须在您的项目中可用的图像

原文链接:https://www.f2er.com/iOS/332784.html

猜你在找的iOS相关文章