如何在编辑文本后重置 tableview 的高度

How do I reset tableview's height after editing text

您好,我正在尝试在编辑文本后重置 tableview 的高度..

第 1 步。选中输入文本视图

第 2 步。在 1 行上输入评论消息..(例如 2 行、3 行..)

第 3 步。点击“发送”按钮

第 4 步。重置 UI

我的问题是..当我将评论输入为 1 行时...它工作正常..

但我确实输入了 2 行或更多行的评论...然后 tableview 的高度没有重置...

你能帮帮我吗?

import UIKit
import Parse

var commentUUID = [String]()
var commentOwner = [String]()

class CommentViewController: UIViewController, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource{

    //UI Objects
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var commentTextView: UITextView!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    var refresher = UIRefreshControl()

    //values for reseting UI to default
    var tableViewHeight : CGFloat = 0
    var commentY : CGFloat = 0
    var commentHeight : CGFloat = 0
    var tableDiff : CGFloat = 0

    //arryas to hold server data
    var usernameArray = [String]()
    var profileArray = [PFFile]()
    var commentArray = [String]()
    var dateArray = [NSDate?]()


    //variable to hold keyboard frame
    var keyboard = CGRect()

    //page size
    var page : Int32 = 15

    override func viewDidLoad() {

        super.viewDidLoad()

        tableView.backgroundColor = UIColor(red: 242.0 / 255.0, green: 242.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)


        //title at the top
        self.navigationItem.title = "COMMENTS"
        self.navigationItem.hidesBackButton = true
//        let backButton = UIBarButtonItem(title: "back", style: .Plain, target: self, action: #selector(CommentViewController.back(_:)))
      let backButton = UIBarButtonItem(image: UIImage(named: "backBtn"), style: .Plain, target: self, action: #selector(CommentViewController.back(_:)))




        self.navigationItem.leftBarButtonItem=backButton


        //swipe to go back
        let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(CommentViewController.back(_:)))
        backSwipe.direction=UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(backSwipe)

        // catch notification if the keyboard is shown or hidden
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)



        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)

        //disable button from the beginning
        sendButton.enabled = false

        loadComments()

        //call function
        alignment()

    }


    //func loading when keyboard is shown
    func keyboardWillShow(notification : NSNotification){

        //define keyboard frame size
        keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue)!

        //move UI up
        UIView.animateWithDuration(0.4){ () -> Void in


            self.bottomConstraint.constant = self.keyboard.height + 4

            self.tableDiff = self.tableView.frame.size.height
        }
    }

    //func loading when keyboard is hidden
    func keyboardWillHide(notification : NSNotification){

        //move UI down
        UIView.animateWithDuration(0.4){() -> Void in


        }

    }

    //alignment function
    func alignment(){


        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 160.0

        //set CommentTextView Style
        commentTextView.layer.cornerRadius = commentTextView.frame.size.width / 50


        //delegates
        commentTextView.delegate = self
        tableView.delegate = self
        tableView.dataSource = self

        //assign reseting values
        tableViewHeight = tableView.frame.size.height
        commentHeight = commentTextView.frame.size.height
        commentY = commentTextView.frame.origin.y


    }



    //while writing something
    func textViewDidChange(textView: UITextView) {

        //disable button if entered no text
        let spacing = NSCharacterSet.whitespaceAndNewlineCharacterSet()

        //It shown when user entered type
        if !commentTextView.text.stringByTrimmingCharactersInSet(spacing).isEmpty{
            sendButton.enabled = true
        }else {

            sendButton.enabled = false
        }


        // + paragraph

        if textView.contentSize.height > textView.frame.size.height && textView.frame.height < 130{

            //find difference to add
            let difference = textView.contentSize.height - textView.frame.size.height
            self.tableDiff = difference

            //redefine frame of commentText
            textView.frame.origin.y = textView.frame.origin.y - difference
            textView.frame.size.height = textView.contentSize.height

            //move up tableView
            if textView.contentSize.height + keyboard.height + commentY >= tableView.frame.size.height {
                tableView.frame.size.height = tableView.frame.size.height - difference


            }

        }

        // - parapraph

        else if textView.contentSize.height < textView.frame.size.height {

            //find difference to deduct
            let difference = textView.frame.size.height - textView.contentSize.height
            self.tableDiff = difference
            //redefine frame of commentText
            textView.frame.origin.y = textView.frame.origin.y + difference
            textView.frame.size.height = textView.contentSize.height

            //move down tableview
            if textView.contentSize.height + keyboard.height + commentY > tableView.frame.size.height {

                tableView.frame.size.height = tableView.frame.size.height + difference
            }

        }


    }

//点击发送按钮 @IBAction func sendButtonTapped(发件人:AnyObject){

    print("send tapped")
    //STEP1. Add row in tableView
    usernameArray.append(PFUser.currentUser()!.username!)
    profileArray.append(PFUser.currentUser()?.objectForKey("profileImg") as! PFFile)
    dateArray.append(NSDate())
    commentArray.append(commentTextView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
    tableView.reloadData()

    //STEP2. Send comment to server
    let commentObj = PFObject(className: "comments")
    commentObj["to"] = commentUUID.last
    commentObj["username"] = PFUser.currentUser()?.username
    commentObj["profileImg"] = PFUser.currentUser()?.valueForKey("profileImg")
    commentObj["comment"] = commentTextView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    commentObj.saveEventually()

    //Scroll to bottom
    self.tableView.scrollToRowAtIndexPath(NSIndexPath(forItem: commentArray.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)

    //STEP 3. Reset UI
    sendButton.enabled = false
    commentTextView.text = ""
    commentTextView.frame.size.height = commentHeight
    commentTextView.frame.origin.y = sendButton.frame.origin.y


    //TableView Reset....Is Not working.
    tableView.frame.size.height = tableView.frame.size.height

}

您似乎在使用自动布局,因此您应该更新约束而不是更新 tableView.frame。为您的 tableView heightConstraint 创建一个 IBOutlet,然后为其设置更新后的高度。

IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!

//calculate the height and update the constant
tableHeightConstraint.constant = updatedTableHeight

另外,从您的代码来看,您似乎只是在更新 tableView.frame.height 本身。您应该计算值并设置为上述约束。