Ios 访问自定义UIView按钮单击操作
我有一个自定义的Ios 访问自定义UIView按钮单击操作,ios,swift,uiview,uisegmentedcontrol,Ios,Swift,Uiview,Uisegmentedcontrol,我有一个自定义的UIView,它复制UISegmentedControl的行为 import UIKit protocol CustomSegmentControlDelegate:class { func change(to index:Int) } class CustomSegmentControl: UIControl { private var buttonTitles:[String]! private var buttons: [UIButton
UIView
,它复制UISegmentedControl
的行为
import UIKit
protocol CustomSegmentControlDelegate:class {
func change(to index:Int)
}
class CustomSegmentControl: UIControl {
private var buttonTitles:[String]!
private var buttons: [UIButton]!
private var selectorView: UIView!
var textColor:UIColor = .black
var selectorViewColor: UIColor = .green
var selectorTextColor: UIColor = .green
weak var delegate:CustomSegmentControlDelegate?
public private(set) var selectedIndex : Int = 0
convenience init(frame:CGRect,buttonTitle:[String]) {
self.init(frame: frame)
self.buttonTitles = buttonTitle
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.backgroundColor = UIColor.white
updateView()
}
func setButtonTitles(buttonTitles:[String]) {
self.buttonTitles = buttonTitles
self.updateView()
}
func setIndex(index:Int) {
buttons.forEach({ $0.setTitleColor(textColor, for: .normal) })
let button = buttons[index]
selectedIndex = index
button.setTitleColor(selectorTextColor, for: .normal)
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(index)
UIView.animate(withDuration: 0.2) {
self.selectorView.frame.origin.x = selectorPosition
}
}
@objc func buttonAction(sender:UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == sender {
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(buttonIndex)
selectedIndex = buttonIndex
delegate?.change(to: selectedIndex)
UIView.animate(withDuration: 0.3) {
self.selectorView.frame.origin.x = selectorPosition
}
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
}
}
在添加了此UIView的单独视图控制器中,我当前无法侦听UIView操作和处理按钮单击<代码>按钮操作不会被调用。单击时不会调用下面的函数
视图通过以下方式添加到VC中:
@IBOutlet weak var segmentView: CustomSegmentControl!
func change(to index: Int) {
print("Inside the function")
}
您能告诉我如何在单独的视图控制器中初始化视图并设置代理吗?请添加明显的细节:是否设置了
delegate
set,是否调用了buttonnaction
操作,…?我已添加了视图初始化,当前未设置代理。代理可能无法工作,您已经添加了segmentView.delegate=self当添加SubView segmentView时?您能告诉我如何在单独的视图控制器中初始化视图并设置代理吗?请添加明显的细节:Isdelegate
set,buttonAction
是否被调用,…?我已经添加了视图初始化,当前未设置委托。委托可能未工作,您已添加了segmentView.delegate=self当添加SubView segmentView时?