Swift:将图像添加到ScrollView

时间:2016-02-04 07:31:35

标签: swift uiimage scrollview

目前我的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 个答案:

答案 0 :(得分:0)

您可以设置按钮图像或按钮背景图像:

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