如何使用keyboardDismissMode = .interactive为键盘滚动设置动画

时间:2016-05-11 16:38:40

标签: ios swift scrollview uikeyboard

我正在创建应用程序的聊天部分,当用户上下滚动scrollview时我遇到键盘动画问题。我正在使用keyboardDismissMode = .Interactive,我无法找到使用它的通知。 default state

这是违约状态。这里我有UIView()用户作为Textview和Button的容器。

当用户只是慢慢向下滚动键盘时,这就是我的问题。当键盘开始移动时,我需要使用containerView移动。

我尝试了UIkeyboardwillChangeFrame,但它没有进行通知。 scrolldown problem

他重新编写了我认为对您有用的代码示例。

import UIKit

struct Message {
var reciever: String?
var sender: String?
var text: String?
var time: String?
}

class ChatMessagesVC: UIViewController, UITextViewDelegate,UIScrollViewDelegate {

var chatID: String?
var recieverName: String?
var recieverId: String?
var recieverPhoto: UIImage?
let scrollView: UIScrollView = UIScrollView()
let textView: UITextView = UITextView()
let sendButton: UIButton = UIButton()
var bottomConstraint: NSLayoutConstraint!
var lastMessageFrom: String = ""
var keyboardRect: CGRect!

let SENDER_BACKGROUND_COLOR: UIColor = .whiteColor()
let SENDER_TEXT_COLOR: UIColor = .blackColor()
let SENDER_FONT: UIFont = UIFont(name: "OpenSans", size: 13)!

let RECIEVER_BACKGROUND_COLOR: UIColor = .yellowColor()
let RECIEVER_TEXT_COLOR: UIColor = .blackColor()
let RECIEVER_FONT: UIFont = UIFont(name: "OpenSans", size: 13)!

// place values
var messageX: CGFloat = 75.0
var messageY: CGFloat = 26.0
var imageX: CGFloat = 10

override func viewDidLoad() {
    super.viewDidLoad()



    if self.recieverName != nil {
        self.title = self.recieverName
    }

    if self.chatID != nil {
        DataModel.instance.CHAT.childByAppendingPath(self.chatID).observeEventType(.ChildAdded, withBlock: {snap in
            var message = Message(reciever: nil, sender: nil, text: nil, time: snap.key)
            if let text = snap.value["text"] as? String {
                message.text = text
            }
            if let sender = snap.value["from"] as? String {
                message.sender = sender
            }
            if let reciever = snap.value["to"] as? String {
                message.reciever = reciever
            }
            if let _ = snap.value["unread"] as? String {
                if message.sender != currentUser.id {
                    DataModel.instance.CHAT.childByAppendingPath(self.chatID).childByAppendingPath(message.time).childByAppendingPath("unread").removeValue()
                }
            }
            self.addMessage(message)

        })
    }

    // notifications about keyboard
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillHide), name:UIKeyboardWillHideNotification, object: nil)


    //BG
    let backgroundView = UIImageView(frame: self.view.bounds)
    let image = UIImage(named: "radarTable")
    backgroundView.image = image
    self.view.addSubview(backgroundView)

    self.textView.delegate = self

    self.view.addSubview(self.scrollView)

    self.scrollView.backgroundColor = .clearColor()
    self.scrollView.delegate = self
    self.scrollView.scrollEnabled = true
    self.scrollView.keyboardDismissMode = .Interactive

    self.textView.font = UIFont(name: "OpenSans", size: 15)
    self.textView.textColor = .whiteColor()
    self.textView.text = NSLocalizedString("chat.placeholder", comment: "")
    self.textView.backgroundColor = .clearColor()
    self.textView.returnKeyType = .Send

    self.sendButton.setTitleColor(.blackColor(), forState: .Normal)
    self.sendButton.setTitle(NSLocalizedString("chat.send", comment: ""), forState: .Normal)
    self.sendButton.titleLabel?.font = UIFont(name: "OpenSans", size: 15)
    self.sendButton.backgroundColor = .orangeColor()
    self.sendButton.addTarget(self, action: #selector(self.sendMessage), forControlEvents: .TouchUpInside)

    // divider

    let divider = UIView()
    divider.backgroundColor = .yellowColor()
    self.view.addSubview(divider)

    // container

    let containerView = UIView()
    containerView.addSubview(self.textView)
    containerView.addSubview(self.sendButton)
    self.view.addSubview(containerView)


    // layout
    self.scrollView.translatesAutoresizingMaskIntoConstraints = false
    self.textView.translatesAutoresizingMaskIntoConstraints = false
    self.sendButton.translatesAutoresizingMaskIntoConstraints = false
    divider.translatesAutoresizingMaskIntoConstraints = false
    containerView.translatesAutoresizingMaskIntoConstraints = false

    let binding = ["scroll": self.scrollView, "text": self.textView, "button": self.sendButton, "div":divider, "container": containerView]

    // horizontal constraints
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scroll]|", options: NSLayoutFormatOptions(), metrics: nil, views: binding))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[div]|", options: NSLayoutFormatOptions(), metrics: nil, views: binding))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[container]|", options: NSLayoutFormatOptions(), metrics: nil, views: binding))

    containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[text]-5-[button(100)]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: binding))


    // vertical constraints
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[scroll]-0-[div(1)]-0-[container(50)]", options: NSLayoutFormatOptions(), metrics: nil, views: binding))

    containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[text]|", options: NSLayoutFormatOptions(), metrics: nil, views: binding))

    containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .CenterY, relatedBy: .Equal, toItem: self.sendButton, attribute: .CenterY, multiplier: 1, constant: 0))
    containerView.addConstraint(NSLayoutConstraint(item: self.sendButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 30))

    self.bottomConstraint = NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)
    self.view.addConstraint(self.bottomConstraint)
}

//MARK: - textview Methods

func textViewDidBeginEditing(textView: UITextView) {
    if textView.text == NSLocalizedString("chat.placeholder", comment: "") {
        textView.text = nil
    }
}

func textViewDidEndEditing(textView: UITextView) {
    if textView.text.isEmpty {
        textView.text = NSLocalizedString("chat.placeholder", comment: "")
    }
}

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        self.sendMessage()
        return false
    }
    return true
}

//MARK: - scrollview functions

//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        let location = scrollView.panGestureRecognizer.locationInView(self.view)
//        if self.keyboardRect != nil {
//            let start = UIScreen.mainScreen().bounds.height - self.keyboardRect.height
//            if location.y > start {
//                self.bottomConstraint.constant = -self.keyboardRect.height - (start - location.y)
//
//            }
//        }
//    }

//MARK: - keyboard notifications

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.keyboardRect = keyboardSize

        UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
            self.bottomConstraint.constant = -keyboardSize.height
            self.view.layoutIfNeeded()
            }, completion: nil)
        let scroll = CGPointMake(0, self.scrollView.contentSize.height - (self.scrollView.bounds.height))
        self.scrollView.setContentOffset(scroll, animated: true)
    }
}

func keyboardWillHide(notification: NSNotification) {

    self.keyboardRect = nil

    UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
        self.bottomConstraint.constant = 0
        self.view.layoutIfNeeded()
        }, completion: nil)

}


//MARK: - chat functions

func addMessage(message: Message) {

    let theWidth = UIScreen.mainScreen().bounds.width

    var messagesSpace:CGFloat = 2

    if self.lastMessageFrom != message.sender {
        //TODO: Dopln cas - neivem ako sa to mas presne spravat a zorbrazovat tak neimplementujem
        messagesSpace += 25
    }



    let messageLbl : UILabel = UILabel()
    messageLbl.frame = CGRectMake(0, 0, self.scrollView.frame.size.width - 100, 0)
    messageLbl.lineBreakMode = NSLineBreakMode.ByWordWrapping
    messageLbl.textAlignment = NSTextAlignment.Left
    messageLbl.numberOfLines = 0
    messageLbl.text = message.text
    messageLbl.sizeToFit()
    messageLbl.frame.origin.y = self.messageY + messagesSpace + 5

    let frame = UIView()



    if message.sender == currentUser.id {

        messageLbl.backgroundColor = self.SENDER_BACKGROUND_COLOR
        messageLbl.textColor = self.SENDER_TEXT_COLOR
        messageLbl.font = self.SENDER_FONT
        messageLbl.frame.origin.x = (self.scrollView.frame.size.width - self.messageX) - messageLbl.frame.width
    } else {

        messageLbl.backgroundColor = self.RECIEVER_BACKGROUND_COLOR
        messageLbl.textColor = self.RECIEVER_TEXT_COLOR
        messageLbl.font = self.SENDER_FONT
        messageLbl.frame.origin.x = self.messageX
    }

    // if should add photo

    if self.lastMessageFrom != message.sender {
        let img:UIImageView = UIImageView()
        img.frame = CGRectMake(self.imageX, self.messageY + messagesSpace, 50, 50)
        self.lastMessageFrom = message.sender!

        if message.sender == currentUser.id {

            img.frame.origin.x = (self.scrollView.frame.size.width - self.imageX) - img.frame.size.width
            img.image = currentUser.photo

        } else {

            img.image = self.recieverPhoto

        }
        img.layer.cornerRadius = img.frame.size.width/2
        img.clipsToBounds = true
        self.scrollView.addSubview(img)
    }

    let bounds = messageLbl.frame
    frame.frame =  CGRectMake(bounds.minX - 10, bounds.minY - 5, bounds.width + 14, bounds.height + 10)
    frame.backgroundColor = messageLbl.backgroundColor

    if message.sender == currentUser.id {
        frame.roundCorners([.TopLeft, .BottomRight, .BottomLeft], radius: 10)

    } else {
        frame.roundCorners([.TopRight, .BottomRight, .BottomLeft], radius: 10)

    }

    self.scrollView.addSubview(frame)
    self.scrollView.addSubview(messageLbl)

    self.messageY += frame.frame.size.height + messagesSpace
    self.scrollView.contentSize = CGSizeMake(theWidth, self.messageY + messagesSpace)

    let bottomOfset:CGPoint = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height)
    self.scrollView.setContentOffset(bottomOfset, animated: true)

}

func scrollViewTapped() {
    self.textView.resignFirstResponder()
}

func sendButtonPressed() {
    textView.resignFirstResponder()
    self.sendMessage()
}

func sendMessage() {
    if self.textView.text != NSLocalizedString("chat.placeholder", comment: "") && !self.textView.text.isBlank {

        let time = NSDate().ToUTCStringWithFormat("yyyy-MM-dd'T'HH:mm:ss")

        let result = ["from":currentUser.id, "to": self.recieverId, "text": self.textView.text, "unread": "true"]

        DataModel.instance.CHAT.childByAppendingPath(self.chatID).childByAppendingPath(time).setValue(result)
        self.textView.text = nil

        DataModel.instance.USERS.childByAppendingPath(currentUser.id).childByAppendingPath("chats").childByAppendingPath(self.chatID).setValue(self.recieverId)
        DataModel.instance.USERS.childByAppendingPath(self.recieverId).childByAppendingPath("chats").childByAppendingPath(chatID).setValue(currentUser.id)
    }
}

1 个答案:

答案 0 :(得分:3)

如果我理解你的问题,我认为你可能想要的是让_containerView成为一个inputAccessoryView,如Apple docs中所述:

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

实施此功能后,您将获得所描述的键盘行为,因为您的视图将被附加"到键盘。