如何设置 UITextField 的 inputAccessoryView 的所需位置?

How to set desired location of UITextField's inputAccessoryView?

为了在 UITextField 的键盘顶部有一个按钮,我这样做了:

class MyTextField: UITextField {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let button = UIButton(type: .system)
        let buttonSize = CGSize(width: button.frame.size.width, height: 50)
        button.frame = CGRect(origin: button.frame.origin, size: buttonSize)
        button.backgroundColor = .orange
        button.setTitleColor(.white, for: .normal)
        button.setTitle("Test", for: .normal)
        inputAccessoryView = button
    }

}

虽然这工作正常,但我想在这里自定义更多按钮的原点和大小,但我找不到这样做的方法。我试过这个:

let buttonSize = CGSize(width: button.frame.size.width - 100, height: 50)
button.frame = CGRect(origin: button.frame.origin, size: buttonSize)

但按钮保持相同的宽度。我能做什么?

感谢您的帮助。

想法是分配给 inputAccessoryView 的视图的框架被忽略,所以创建一个透明颜色的视图并向其中添加任何项目,你可以试试这个

class MyTextField: UITextField {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        let button = UIButton(type: .system)
        button.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.size.width-100,height: 50)
        button.backgroundColor = .orange
        button.setTitleColor(.white, for: .normal)
        button.setTitle("Test", for: .normal)
        let rr = UIView()
        rr.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.size.width,height: 50)
        rr.backgroundColor = UIColor.clear;
        inputAccessoryView = rr
        rr.addSubview(button)
    }


}

class MyTextField: UITextField {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let button = UIButton(type: .system)
        button.frame = CGRect(x:50, y:5, width: UIScreen.main.bounds.size.width-100,height: 50)
        button.backgroundColor = .orange
        button.setTitleColor(.white, for: .normal)
        button.setTitle("Test", for: .normal)

        let aframe = CGRect(x:0, y:0, width: UIScreen.main.bounds.size.width,height: 60)
        let accessory = UIView(frame: aframe)
        accessory.backgroundColor = .clear
        accessory.addSubview(button)

        inputAccessoryView = accessory
    }

}