【发布时间】:2021-10-16 17:53:45
【问题描述】:
用以下两种方式之一帮助我:
- 如何解决问题?或
- 如何理解错误信息?
项目总结
所以我通过制作一个只有一个UIButton 的小项目来了解inputAccessoryView。点击该按钮会调用带有inputAccessoryView 的键盘,其中包含1 个UITextField 和1 个UIButton。 inputAccessoryView 中的 UITextField 将是最后一个 firstResponder,它负责与 inputAccessoryView 一起使用的键盘
错误信息
API error: <_UIKBCompatInputView: 0x7fcefb418290; frame = (0 0; 0 0); layer = <CALayer: 0x60000295a5e0>> returned 0 width, assuming UIViewNoIntrinsicMetric
代码
如下所示非常简单
- 自定义
UIView用作inputAccessoryView。它安装了 2 个 UI 插座,并告诉响应者链它canBecomeFirstResponder。
class CustomTextFieldView: UIView {
let doneButton:UIButton = {
let button = UIButton(type: .close)
return button
}()
let textField:UITextField = {
let textField = UITextField()
textField.placeholder = "placeholder"
return textField
}()
required init?(coder: NSCoder) {
super.init(coder: coder)
initSetup()
}
override init(frame:CGRect) {
super.init(frame: frame)
initSetup()
}
convenience init() {
self.init(frame: .zero)
}
func initSetup() {
addSubview(doneButton)
addSubview(textField)
}
func autosizing(to vc: UIViewController) {
frame = CGRect(x: 0, y: 0, width: vc.view.frame.size.width, height: 40)
let totalWidth = frame.size.width - 40
doneButton.frame = CGRect(x: totalWidth * 4 / 5 + 20,
y: 0,
width: totalWidth / 5,
height: frame.size.height)
textField.frame = CGRect(x: 20,
y: 0,
width: totalWidth * 4 / 5,
height: frame.size.height)
}
override var canBecomeFirstResponder: Bool { true }
override var intrinsicContentSize: CGSize {
CGSize(width: 400, height: 40)
} // overriding this variable seems to have no effect.
}
- 主VC使用自定义
UIView作为inputAccessoryView。 inputAccessoryView 中的UITextField最终会变成真正的firstResponder,我相信。
class ViewController: UIViewController {
let customView = CustomTextFieldView()
var keyboardShown = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
customView.autosizing(to: self)
}
@IBAction func summonKeyboard() {
print("hello")
keyboardShown = true
self.becomeFirstResponder()
customView.textField.becomeFirstResponder()
}
override var canBecomeFirstResponder: Bool { keyboardShown }
override var inputAccessoryView: UIView? {
return customView
}
}
- 我在互联网上看到有人说如果我在实体手机上运行,此错误消息就会消失。当我尝试时,我并没有离开。
- 我覆盖了自定义视图的
intrinsicContentSize,但是没有效果。 - 当我点击
summon时,错误消息同时显示两次。 - 错误消息指的是什么“框架”或“层”?它是指自定义视图的框架和层吗?
【问题讨论】:
标签: ios uiview autolayout uitextfield inputaccessoryview