在选择UITextField上滚动UIScrollView,无法获得正确的大小

时间:2015-05-23 13:10:31

标签: ios swift uiscrollview

我所拥有的是一个带有容器视图的UIScrollView。它嵌入了一个包含静态单元格的UITableViewcontroller。当我在静态单元格中选择UITextField时,我想滚动UIScrollView。我尝试了两种方法,1。计算位置,2。计算单元格索引。当我选择任何UIField时,这两种方式都会保持相同的值。有人可以帮我解决这个问题吗?

我用过这个问题: How do I scroll the UIScrollView when the keyboard appears?

    func keyboardWasShown(notification : NSNotification){

        var info = notification.userInfo

//        var kbSize = info(UIKeyboa
        if let userInfo = notification.userInfo {
            if let kbSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
                let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: kbSize.height, right: 0)

                scrollView.contentInset = contentInsets;
                scrollView.scrollIndicatorInsets = contentInsets;


                //first approach
                println("---- approach 1 ------")
                var activeField = self.container?.groupField.superview?.superview
                println(activeField!.frame.origin)
                //prints (110.0, 5.0)



                //second approach
                println("---- approach 2 ------")
                var cell =  self.container?.groupField.superview?.superview as! UITableViewCell
                var table =  self.container?.view as! UITableView
                var index = table.indexPathForCell(cell)
                println("index: \(index?.row)") 
                //prints always 4



                var aRect = self.view.frame
                aRect.size.height -= kbSize.height
//                println("aRect: \(aRect)")
                if (!CGRectContainsPoint(aRect, activeField!.frame.origin) ) {
                    println("ActiveField: \(activeField!.frame.origin.y)")
                    var scrollPoint = CGPointMake(0.0, activeField!.frame.origin.y-kbSize.height)
                    scrollView.setContentOffset(scrollPoint, animated:true)
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

这是一个愚蠢的错误,我选择了默认字段作为活动字段

我换了: var activeField = self.container?.groupField.superview?.superview

于: var activeField = self.container?.activeField.superview?.superview