gpt4 book ai didi

ios - 使用必要的数据源和委托(delegate)扩展 UIView

转载 作者:行者123 更新时间:2023-11-28 08:46:39 24 4
gpt4 key购买 nike

我想在 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,此时未设置数据源和委托(delegate),因此 ITISegmentedView 不起作用。

最佳答案

当遇到 nil 时回退到空的 dataSource

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

关于ios - 使用必要的数据源和委托(delegate)扩展 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35129723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com