Hél*_*tin 11 ios uicollectionview swift
我正在实现一个控件,其行为类似于NSTokenField(例如,Mail中的地址选择器),以便在iOS中使用.我使用横向UICollectionView,我最右边的单元格是UITextField.此控件将以包含右对齐文本的其他文本字段的形式显示.为了让我的新控件在这个上下文中看起来正确,我希望UITextField始终位于它的右边缘,UICollectionView并且选定的标签显示在它的左侧.
目前,当我第一次点击此行时,文本字段向左滚动,然后在添加更多标签时将其推到右侧.一旦它与右边缘齐平UICollectionView(当下图中添加'开胃菜')时,我开始得到我想要的行为.
我一直在考虑类似于最小宽度的东西,UITextField因此它占用的宽度与最初可用的宽度相同,并且随着标签的添加越来越少.或者,通过某种方式将固定字段固定到右侧.但是,我还没有找到实现这些想法的方法!
我怎样才能使文本字段始终位于右侧UICollectionView?
这是一个解决方案,其中UITextField不是UICollectionView的一部分.
我在我的故事板上添加了collectionView和textField,其中包含以下布局约束: CollectionView:导向superview,Height,Top to superview,使用textField的水平间距. 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)
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
作为 UICollectionViewDataSource 的一部分
尝试使用
// 返回的视图必须通过调用 -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
并将包含文本字段的视图定义为页脚。