My approach was this:
- Create a scrollable view
- create an offset of say 10 for padding between chips
- Add chips to the scrollable view
- Set the frame origin of the chip with the declared offset
- Add the chip's width to the offset plus the initial offset value (in this case 10)
- Increase the content width of the scrollable view, set the width to the total
offset
- (add more chips/repeat)
On chip removal (if needed)
- Set initial offset back to 10
- Remove chip from parent scrollable view
- Loop through subviews and set the offset again to each of them
- Set the scrollable view new width using the total offset
Here is a sample in Swift
Configure initial layout
class ChipSample
{
var tagXOffset = 10
var tagPadding = 10
func configureTagsView()
{
tagView = UIScrollView(frame: CGRect(x: 0, y: 120, width: view.bounds.width, height: 40))
view.addSubview(tagView)
}
Add a chip
func addChip(name:String)
{
let chip = MDCChipView()
chip.titleLabel.text = name
chip.setTitleColor(.gray, for: .normal)
chip.sizeToFit()
chip.addTarget(self, action: #selector(removeChip), for: .touchUpInside)
tagView.addSubview(chip)
chip.frame.origin.x = tagXOffset
chip.frame.origin.y = 0
tagXOffset += tagPadding + chip.frame.width
tagView.contentSize = CGSize(width: tagXOffset, height: tagViewHeight)
}
Remove the chip
@objc func removeChip(sender: MDCChipView!)
{
tagXOffset = tagPadding
sender.removeFromSuperview()
for subview in tagView.subviews {
subview.frame.origin.x = tagXOffset
tagXOffset += tagPadding + subview.frame.width
}
}