1
votes

I want in UITableViewCell add customized UIView (will be analog segmented control) I wrote subclass `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
    }
}

}`

In storyboard added UIView and set class ITISegmentedView

in my ViewController:

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

PROBLEM: init(coder aDecoder: NSCoder) calls on dequeueReusableCell and at this moment data source and delegate is not set, so ITISegmentedView doesn't work.

1

1 Answers

0
votes

Fall back to an empty dataSource when you encounter nil.

Also, try not to use !, but rather ? and ?? to always take into account that an Optional is... well. Optional.