【问题标题】:How to set desired location of UITextField's inputAccessoryView?如何设置 UITextField 的 inputAccessoryView 的所需位置?
【发布时间】:2018-03-27 13:49:24
【问题描述】:

为了让我的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)

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

感谢您的帮助。

【问题讨论】:

    标签: ios uitextfield inputaccessoryview


    【解决方案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)
        }
    
    
    }
    

    【讨论】:

    • 很好的解决方案。谢谢!
    【解决方案2】:
    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
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      相关资源
      最近更新 更多