UIPageControl自定义类 - 发现nil将图像更改为点

时间:2015-01-14 10:53:52

标签: ios swift null uipagecontrol

我需要使用自定义图像而不是普通点来实现UIPageControl。所以我创建了一个自定义类并通过故事板连接它。 从ios7开始,UIPageControl的子视图包含UIView而不是UIImageView。生成的UIViewUIIpageControl子视图)的子视图不包含任何子视图,因此我收到错误消息:

  

致命错误:在解包可选值时意外发现nil

我可能错在哪里?

class WhitePageControl:UIPageControl{
   let activeImage = UIImage(named: "dot_white")
   let inactiveImage = UIImage(named: "dot_white_e")

   override init(frame: CGRect){
     super.init(frame: frame)
   }

   required init(coder aDecoder: NSCoder){
     super.init(coder: aDecoder)
   }

   func updateDots(){
     println(self.subviews.count) // 3
     println(self.numberOfPages) // 3
     for var index = 0; index < self.subviews.count; index++ {
        println(index)
        var dot:UIImageView!
        var dotView:UIView = self.subviews[index] as UIView
        println("1")
        for subview in dotView.subviews{ // NIL HERE
            println("2")
            if subview.isKindOfClass(UIImageView){
                println("3")
                dot = subview as UIImageView
                if index == self.currentPage{ dot.image = activeImage }
                else{ dot.image = inactiveImage }
            }
            }
         }
       }

    func setCurrentPage(value:Int){
        super.currentPage = value
        self.updateDots()
    }
}

2 个答案:

答案 0 :(得分:5)

这是我的解决方案:

import Foundation

class PageControl: UIPageControl {
    var activeImage: UIImage!
    var inactiveImage: UIImage!
    override var currentPage: Int {
        //willSet {
        didSet { //so updates will take place after page changed
            self.updateDots()
        }
    }

    convenience init(activeImage: UIImage, inactiveImage: UIImage) {
        self.init()

        self.activeImage = activeImage
        self.inactiveImage = inactiveImage

        self.pageIndicatorTintColor = UIColor.clearColor()
        self.currentPageIndicatorTintColor = UIColor.clearColor()
    }

    func updateDots() {
        for var i = 0; i < count(subviews); i++ {
            var view: UIView = subviews[i] as! UIView
            if count(view.subviews) == 0 {
                self.addImageViewOnDotView(view, imageSize: activeImage.size)
            }
            var imageView: UIImageView = view.subviews.first as! UIImageView
            imageView.image = self.currentPage == i ? activeImage : inactiveImage
        }
    }

    // MARK: - Private

    func addImageViewOnDotView(view: UIView, imageSize: CGSize) {
        var frame = view.frame
        frame.origin = CGPointZero
        frame.size = imageSize

        var imageView = UIImageView(frame: frame)
        imageView.contentMode = UIViewContentMode.Center
        view.addSubview(imageView)
    }

}

答案 1 :(得分:0)

将setCurrentPage更改为Current Page,bcoz一个是Obj C属性

 func currentPage(page: Int) {
    super.currentPage = page
    self.updateDots()
}

试试这个。