使用必要的dataSource和delegate扩展UIView

时间:2016-02-01 11:46:18

标签: ios swift uiview

我想在UITableViewCell中添加自定义的UIView(将是模拟分段控件) 我写了子类`protocol ITISegmentedViewDelegate:class {     func segmentedViewButtonChanged(index:Int) }

public protocol ITISegmentedViewDataSource : NSObjectProtocol {

@available(iOS 2.0, *)
func segmentedView(itemsInSegmentedView: ITISegmentedView) -> [String]
}

public class ITISegmentedView: UIView {

    var delegate: ITISegmentedViewDelegate?
    var dataSource: ITISegmentedViewDataSource?
    var selectedItem = -1

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

    }

    required public init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

    self.addButtons()
}

private func addButtons(){
    if delegate == nil || dataSource == nil{
        return
    }

    let height = frame.height
    let width = frame.width

    let array = dataSource!.segmentedView(self)
    let totalItem = array.count

    var startX = CGFloat(0)

    for var index = 0; index < totalItem; ++index{
        let button = UIButton(frame: CGRectMake(startX, 0, width/CGFloat(totalItem), height))
        button.setTitle(array[index], forState: UIControlState.Normal)
        button.tag = index
        button.addTarget(button, action: "onButtonPressed", forControlEvents: .TouchUpInside)
        startX += width/CGFloat(totalItem)
        addSubview(button)
    }

    if totalItem>0{
        selectedItem = 0
        delegate?.segmentedViewButtonChanged(0)
    }
}



func onButtonPressed(button: UIButton){
    if selectedItem != button.tag{
        delegate?.segmentedViewButtonChanged(button.tag)
        selectedItem = button.tag
    }
}

}`

在storyboard中添加了UIView并设置了类ITISegmentedView

在我的ViewController中

let cell = tableView.dequeueReusableCellWithIdentifier( cellName, forIndexPath: indexPath)
let seg = (cell.viewWithTag(1) as! ITISegmentedView)
seg.dataSource = self
seg.delegate = self

问题: init(coder aDecoder:NSCoder)调用dequeueReusableCell,此时数据源和委托没有设置,因此ITISegmentedView不起作用。

1 个答案:

答案 0 :(得分:0)

遇到dataSource时,请回到空nil

另外,尽量不要使用!,而是使用???来始终考虑Optional是......好吧。可选的。