UICollectionView - 当键盘出现时,整个集合视图随键盘移动 [英] UICollectionView - When the keyboard appears the entire collection view is shifted with the keyboard

查看:27
本文介绍了UICollectionView - 当键盘出现时,整个集合视图随键盘移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是我想要的效果.这只发生在集合视图设置为水平流布局时.我看过其他一些关于这个问题的帖子,但提供的答案都没有奏效.有人找到解决方案了吗?

This isn't my desired effect. This only happens when the collection view is set to horizontal flow layout. I've seen a few other posts regarding this very same issue but none of the provided answers have worked. Has anyone found a solution?

我提供了两个屏幕截图,显示了触发键盘之前和之后的 UITextField.如您所见,UITextField 以及整个集合视图(看不到)与键盘一起被向上推.通常键盘被覆盖,对视图没有影响.

I've provided two screenshots showing a UITextField before the keyboard is triggered and after. As you can see the UITextField along with the entire collection view (which can't be seen) is pushed up along with the keyboard. Usually the keyboard is overlayed having no effect on the views.

之前

之后

更新提供的代码.我用来实现的方法不涉及故事板.

Update Code provided. The method I used to implement doesn't involve a Storyboard.

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    window = UIWindow()
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let rvc = ViewController(collectionViewLayout: layout)
    window?.rootViewController = rvc

    return true
}

// .... other boilerplate code provided by Apple when you make a new App
}

ViewController.swift

ViewController.swift

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
    let homeCellId = "homeCellId"
    let worldCellId = "worldCellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        collectionView?.register(HomeCell.self, forCellWithReuseIdentifier: homeCellId)
        collectionView?.register(WorldCell.self, forCellWithReuseIdentifier: worldCellId)
collectionView?.isPagingEnabled = true
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        print(indexPath.item)
        let identifier: String
        if indexPath.item == 0 {
            identifier = homeCellId
        } else if indexPath.item == 1 {
            identifier = worldCellId
        }
        else {
            identifier = homeCellId
        }

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
        cell.backgroundColor = UIColor.blue
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

MyCell.swift

MyCell.swift

class MyCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupView() {

    }


}

HomeCell.swift

HomeCell.swift

class HomeCell: MyCell {
    let weightField: UITextField = UITextField(frame: .zero)
    override func setupView() {
        super.setupView()
        print("HomeCell")
        weightField.backgroundColor = UIColor.white
        weightField.translatesAutoresizingMaskIntoConstraints = false
        weightField.keyboardType = UIKeyboardType.default
        self.addSubview(weightField)

        weightField.topAnchor.constraint(equalTo: self.topAnchor, constant: 200).isActive = true
        weightField.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 50).isActive = true
    }


}

WorldCell.swift

WorldCell.swift

//与 HomeCell 相同

// same as HomeCell

class WorldCell: MyCell {

    override func setupView() {
        super.setupView()
        print("worldcell")
    }


}

推荐答案

好的,我找到了解决这个问题的方法.我在 stackoverflow 上关于类似事件的其他几个线程中遇到了这一点,在一种情况下,答案没有归因于它的投票,并且对答案留下的评论说它不起作用..

Okay so I've found a solution to this problem. I came across this in a couple of other threads on stackoverflow regarding a similar incident, in one case the Answer had no votes attributed to it and a comment left to the answer said it didn't work..

尽管如此,我仍然不清楚为什么其他实现会导致集合视图向上移动.尽管窗口、根视图控制器和它的子视图以及键盘之间存在一些相关性.为什么会发生这种情况我不知道.

Though after all this I'm still not crystal clear on why the other implementation causes the collection view to shift up. Though there is some correlation between the window, root view controller and it's subviews along with the keyboard. Why this happens I don't know.

现在开始代码并修复..

Now on to the code and fix..

上述问题中的方法与此处的主要区别在于集合视图的初始化方式.我只会发布我更改的内容,因为其余部分相同.

The main different between the method in the question above and here is the way the collection view is initialised. I'll only post what I changed because the rest is just the same.

AppDelegate.swift

AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let rvc = ViewController()

        window? = UIWindow()
        window?.makeKeyAndVisible()
        window?.rootViewController = rvc
        return true
    }
}

这里的显着区别是根视图控制器不再使用集合视图控制器初始化.我们使用标准的视图控制器.

The striking difference here is the root view controller is no longer initialised with the Collection View Controller. We use a standard View Controller.

ViewController.swift

ViewController.swift

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var collView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.dataSource = self
        view.delegate = self
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.darkGray
        collView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        collView.register(HomeCell.self, forCellWithReuseIdentifier: "homeCellId")
        self.view.addSubview(collView)
        collView.backgroundColor = UIColor.blue
        collView.translatesAutoresizingMaskIntoConstraints = false
        collView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        collView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        collView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        collView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        collView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 1)
        // Do any additional setup after loading the view, typically from a nib.
    }
}

我们用一个collectionview作为一个子视图来初始化视图控制器,并应用我们通常对单元格相同的代码

We initialise the View Controller with a collectionview as a subview and apply the same code we would normally to the cells

这篇关于UICollectionView - 当键盘出现时,整个集合视图随键盘移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆