选择上部UITextField时向下滚动UIScrollView

时间:2016-01-27 19:16:53

标签: ios iphone swift uiscrollview uitextfield

我有一个带有ContentView的ScrollView,它有5个UITextField。我已经实现了adjustForKeyboard:

import MySQLdb
import time

# Create a database connection
db = MySQLdb.connect(host="******", user="******", passwd="*****", db="*****")
cur = db.cursor()

# Create a query to select all IDs
cur.execute("SELECT id FROM users")
clientArray = []

# Loop over all IDs returned from query,
# save all IDs in the clientArray
for row in cur.fetchall():
    clientID = str(row[0])
    clientArray.append(clientID)


clientIDInput = ""    
while True:
    # Check and wait for input
    clientIDInput = raw_input("")
    if clientIDInput in clientArray:
        # Check to see whether user is already signed in to the device
        cur.execute("SELECT fitnessStatus FROM users WHERE id=%s", (clientIDInput))
        data = cur.fetchone()
        if data[0] == False:
            cur.execute("UPDATE users SET fitnessStatus='1' WHERE id=%s", (clientIDInput))
            checkInTime = time.strftime('%Y-%m-%d %H:%M:%S')
            checkOutID = raw_input("")
            if checkOutID == clientIDInput:
                cur.execute("UPDATE users SET fitnessStatus='0' WHERE id=%s", (clientIDInput))
                checkOutTime = time.strftime('%Y-%m-%d %H:%M:%S')
                print checkInTime
                print checkOutTime

                ### I BELIEVE THIS IS THE CAUSE OF THE ERROR ###
                cur.execute("INSERT INTO activities (id, machinename, checkin, checkout, clientid) VALUES (NULL, Cross Trainer #5, %s, %s, %s)", (checkInTime, checkOutTime, clientIDInput))
                # Send checkInTime and checkOutTime to database

当然,我已经设立了观察员:

func adjustForKeyboard(notification: NSNotification) {
    let userInfo = notification.userInfo!

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)

    if notification.name == UIKeyboardWillHideNotification {
        scrollView.contentInset = UIEdgeInsetsZero
    } else {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
    }

    scrollView.scrollIndicatorInsets = scrollView.contentInset

}

当我从上到下选择TextFields时它工作正常,但当我选择一个上部TextField时,它只移动几个像素。我应该如何改变我的方法?

1 个答案:

答案 0 :(得分:0)

更改底部的contentInset不会使scrollView滚动。它在底部设置一个缓冲区,所以如果你一直滚动到底部,它将有更多的空间滚动。

您想要修改scrollView的contentOffset并为contentOffset更改设置动画。你会做这样的事情:

var contentOffset = scrollView.contentOffset
contentOffset.y = contentOffset.y + (however much you want it to move)
scrollView.setContentOffset(contentOffset, animated: true)

这将允许它根据选择的textField向上和向下滚动。