我写了一个自定义UITextField
,并使用inputAccessoryView
在键盘上方添加了一个按钮。
代码如下:
class CustomTextField: UITextField {
var button: UIButton?
var buttonContainer: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
redraw()
}
override init(frame: CGRect) {
super.init(frame: frame)
redraw()
}
private func redraw() {
button = UIButton()
button?.setTitle("BUTTON TEST", for: .normal)
button?.backgroundColor = .red
let dividend: CGFloat = isPortraitOrientation ? 56 : 1
let divisor: CGFloat = isPortraitOrientation ? 326 : 18
let buttonHeight = ((UIScreen.main.bounds.width - 48) * dividend) / divisor
button?.frame = CGRect(origin: CGPoint(x: 24, y: 0), size: CGSize(width: UIScreen.main.bounds.width - 48, height: buttonHeight))
buttonContainer = UIView()
buttonContainer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: buttonHeight + 10)
buttonContainer?.backgroundColor = .clear
inputAccessoryView = buttonContainer!
buttonContainer?.addSubview(button!)
}
func updateView() {
redraw()
}
}
在控制器中:
class CustomViewController: UIViewController {
@IBOutlet weak var textField: CustomTextField!
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { _ in
self.textField.updateView()
}
}
}
当我第一次旋转屏幕,然后开始编辑文本字段时,button
和buttonContainer
都正确显示。但是旋转手机时,它们没有正确重绘。
感谢您的帮助。