【问题标题】:Extend UIView with necessary dataSource and delegate使用必要的数据源和委托扩展 UIView
【发布时间】:2016-05-09 20:33:15
【问题描述】:

我想在 UITableViewCell 中添加自定义的 UIView(将是模拟分段控件) 我写了子类`protocol ITISegmentedViewDelegate: class { func segmentedViewButtonChanged(索引: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
    }
}

}`

在故事板中添加 UIView 并设置类 ITISegmentedView

在我的视图控制器中:

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 不起作用。

【问题讨论】:

    标签: ios swift uiview


    【解决方案1】:

    遇到nil时,退回到空的dataSource

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

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2011-09-21
      • 2016-05-20
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多