首页 > 解决方案 > iOS:旋转后 UITextField 的 inputAccessoryView 没有更新

问题描述

我写了一个自定义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但是在旋转手机时它们没有正确重绘。

谢谢你的帮助。

标签: iosrotationuitextfieldinputaccessoryview

解决方案


推荐阅读