将水平UICollectionView中的一个单元格固定到右侧

时间:2016-09-26 11:53:14

标签: ios swift uicollectionview

我正在实现一个控件,其行为类似于NSTokenField(例如Mail中的地址选择器),以便在iOS中使用。我使用水平UICollectionView,最右边的单元格是UITextField。此控件将以包含右对齐文本的其他文本字段的形式显示。为了让我的新控件在此上下文中正确显示,我希望UITextField始终位于UICollectionView的右边缘,并且所选标记显示在其左侧。

目前,当我第一次点击此行时,文本字段向左滚动,然后在添加更多标签时将其推到右侧。一旦它与UICollectionView的右边缘齐平(当下图中添加了'开胃菜'),我就开始得到我想要的行为。

Tag selection

我一直在考虑像UITextField上的最小宽度这样的东西,所以它占用的宽度与最初可用的宽度一样多,而且随着标签的添加越来越少。或者,通过某种方式将固定字段固定到右侧。但是,我还没有找到实现这些想法的方法!

我怎样才能使文本字段始终位于UICollectionView

的右侧

3 个答案:

答案 0 :(得分:5)

这是一个UITextField不属于UICollectionView的解决方案。

enter image description here

我在故事板上添加了collectionView和textField,其中包含以下布局约束: CollectionView :通过textField导向superview,Height,Top to superview,水平间距。 TextField :高度等于collectionView,尾随到superview,宽度= 100,水平间距与collectionView。

我为textField的宽度约束创建了一个IBOutlet。输入文本时,宽度会动态更改。

Swift 3示例代码

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var textFieldWidthConstraint: NSLayoutConstraint!

    var textArray: [String] = [String]()

    @IBAction func editingChanged(_ sender: AnyObject) {
        let size = textField.sizeThatFits(textField.frame.size)
        textFieldWidthConstraint.constant = max(size.width,100)

        if textArray.count > 0 {
            self.collectionView.scrollToItem(at: IndexPath(row: self.textArray.count-1, section: 0), at: .right, animated: true)
        }
    }

    @IBAction func addText(_ sender: AnyObject) {
        if textField.text?.characters.count ?? 0 > 0 {
            textArray.append(textField.text!)
            textField.text = ""
            textFieldWidthConstraint.constant = 100
            let newIndexPath = IndexPath(row: textArray.count-1, section: 0)
            collectionView.insertItems(at: [newIndexPath])
            collectionView.performBatchUpdates({
                }, completion: { (_) in
                    self.collectionView.scrollToItem(at: newIndexPath, at: .right, animated: true)
            })
        }
    }

}

答案 1 :(得分:0)

作为UICollectionViewDataSource的一部分

尝试使用

//必须从对-dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath的调用中检索返回的视图: - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

并定义包含文本字段作为页脚的视图。

答案 2 :(得分:0)

为了完整起见,以防万一有人给我个主意,我最终按照this answer中的描述,只强加了UICollectionView上从右到左的顺序。这意味着新标签会直接显示在UITextField的左侧,这可以满足我的需求。

相关问题