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

时间:2018-03-27 13:49:24

标签: ios uitextfield 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
    }

}

enter image description here

虽然这很好用,但我想在这里自定义按钮的来源和大小,但我找不到办法。我尝试了这个:

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

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这个想法是分配给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)
    }


}

enter image description here

答案 1 :(得分:1)

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
    }

}