使用滚动视图时保持对象的位置

时间:2016-11-25 07:42:26

标签: ios swift scrollview textfield

我几天前发布了此消息,但似乎无法找到有效的解决方案。

(1)这是屏幕的整体布局。该按钮位于滚动视图内,因此当显示按钮时,该按钮将被推送到用户视图。然后在第一个响应者辞职时退回。我希望文本字段完全移动。我想把它们放在我放置它们的位置。只有按钮才是我想要移动的。

(1)https://i.stack.imgur.com/O8iJy.png

(2)键盘出现时的结果。它最终将文本字段推出视图。

(2)https://i.stack.imgur.com/VDhdI.png

这是我正在使用的代码:     @IBOutlet weak var ScrollView:UIScrollView!

@IBOutlet weak var TextField: UITextField!

@IBOutlet weak var testButton: UIButton!

@IBOutlet weak var testView: UIView!
func closeKeyboard(){
    self.view.endEditing(true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    closeKeyboard()
}

    override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(scrollviewtest.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(scrollviewtest.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    }

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }

1 个答案:

答案 0 :(得分:0)

而不是

X1   
1   0.1097075
2   0.6081752
3   0.9912855
4   0.8543848
5   0.2579654
6   0.6203840 
7   0.6643195
8   0.5760624
9   0.8888167
10  0.8926815
11 50.230000

self.view.frame.origin.y -= keyboardSize.height

您必须为按钮底部创建NSLayoutConstraint以滚动视图底部,然后使用此约束进行操作。代码看起来像这样。

keyboardWillShow

约束将看起来像这样:

enter image description here