2016-02-04 84 views
-1

目前我的ScrollView中有按鈕的顏色,但我希望這些按鈕具有圖像而不是它們的顏色。所以,我想徹底擺脫我目前在我的代碼中的顏色,並用圖像替換它們。這裏是我的代碼:Swift:將圖像添加到ScrollView中

@IBOutlet weak var categoryScrollView: UIScrollView! 


    var categoryArr = ["Button1","Button2","Button3","Button4","Button5", "Button 6", "Button 7", "Button 8", "Button 9", "Button 10", "Button 11", "Button 12"] 
    var buttonColors = [UIColor.greenColor(), UIColor.blueColor(), UIColor.blackColor(), UIColor.cyanColor(), UIColor.magentaColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.blackColor(), UIColor.cyanColor(), UIColor.magentaColor(), UIColor.blackColor(), UIColor.brownColor()] 

//var buttonColors = [String?]() 
    let kPadding:CGFloat = 20 


    override func viewDidLoad() { 
     super.viewDidLoad() 



     let buttonSize = CGSizeMake(categoryScrollView.bounds.size.width/2, categoryScrollView.bounds.size.height/2)//hal 

     let scrollingView = colorButtonsView(buttonSize, buttonCount: 12) 
     categoryScrollView.contentSize = scrollingView.frame.size 
     categoryScrollView.addSubview(scrollingView) 
     categoryScrollView.showsVerticalScrollIndicator = false 
     categoryScrollView.delegate = self 
     categoryScrollView.pagingEnabled = true 
     categoryScrollView.indicatorStyle = .Default 
     categoryScrollView.contentOffset = CGPointMake(0, 0) 
    } 


    func colorButtonsView(buttonSize:CGSize, buttonCount:Int) -> UIView { 

     //let images: [UIImage] = [UIImage(named: "image1.png")!, UIImage(named: "image2.png")!] 


     let buttonView = UIView() 
     buttonView.frame.origin = CGPointMake(50,142) 
     let padding = CGSizeMake(kPadding, kPadding) 
     buttonView.frame.size.width = (buttonSize.width + padding.width) * CGFloat(buttonCount) 
     var buttonPosition = CGPointMake(0, padding.height) 
     let buttonIncrement = buttonSize.width + padding.width 
     for i in 0...(buttonCount - 1) { 
      let button = UIButton(type: .Custom) 
      button.frame.size = buttonSize 
      button.frame.origin = buttonPosition 
      buttonPosition.x = buttonPosition.x + buttonIncrement 
      button.setTitle(categoryArr[i], forState: UIControlState.Normal) 
      button.backgroundColor = buttonColors[i] 
      button.layer.cornerRadius = 30 
      buttonView.addSubview(button) 
      //self.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside) 
     } 
     buttonView.backgroundColor = UIColor.redColor() 
     return buttonView 
    } 
} 
extension ViewController:UIScrollViewDelegate{ 
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) { 

     let index = round(scrollView.contentOffset.x/scrollView.frame.size.width) 
     print(index) 
    } 

}

+1

我不明白你的問題。你爲什麼不設置按鈕圖像?它與ScrollView有什麼關係?更少的代碼和更好的描述請。 – Tapani

+0

對不起,讓我更加清楚。我不知道如何設置按鈕圖像。我只是認爲你這樣做的方式可能會有所不同,因爲按鈕在ScrollView中。 –

回答

0

您可以設置按鈕圖像或按鈕背景圖片:

button.setBackgroundImage(image: UIImage?, forState: UIControlState) 
button.setImage(image: UIImage?, forState: UIControlState)