【发布时间】:2020-12-04 11:31:25
【问题描述】:
我正在尝试创建一个子类 UILabel 并具有 UISegmentedControl 属性的自定义标签。本质上,我正在尝试创建一个自定义按钮。
视图和约束已添加到父视图中,但 UISegmentedControl 对触摸没有响应。下面是我如何尝试使用它的代码 sn-p。我尝试启用 isUserInteractionEnabled 作为健全性检查,但没有任何反应。
class CustomLabelWithSelector: CustomLabel {
var selector: UISegmentedControl!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(with title: String) {
super.init(with: title)
selector = UISegmentedControl(frame: .zero)
selector.insertSegment(withTitle: "Off", at: 0, animated: true)
selector.insertSegment(withTitle: "On", at: 1, animated: true)
selector.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
selector.selectedSegmentTintColor = .systemGray
selector.backgroundColor = .tertiarySystemFill
selector.selectedSegmentIndex = 0
selector.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(selector)
selectorConstraints()
}
private func selectorConstraints() {
selector.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
selector.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -5).isActive = true
}
}
class ViewController: UIViewController {
var customLabelWithSelector: CustomLabelWithSelector!
init() {
self.setUpView()
}
func setupView() {
customLabelWithSelector = CustomLabelWithSelector(with: " Option")
view.addSubview(customLabelWithSelector)
// Label does not respond to touch, nor is the function called below
customLabelWithSelector.selector.addTarget(self, action: #selector(selectOnOff(_:)), for: .valueChanged)
}
@objc func selectOnOff(_ segmentedControl: UISegmentedControl) {
switch (segmentedControl.selectedSegmentIndex) {
case 0:
print("off selected")
break
case 1:
print("on selected")
break
default:
print("default")
break
}
}
}
我还自己对我的 UISegmentedControl 进行了子类化,并成功地将其作为子视图添加到父 UIView。它确实响应了触摸(从关闭切换到开启),也没有调用该函数。
我错过了什么吗?我可能不太了解视图层次结构,但我也尝试将 UISegmentedControl 视图置于最前面,但也没有用。
关于如何实现这个有什么建议吗?
【问题讨论】:
标签: ios swift uilabel subclass uisegmentedcontrol