2

I am trying to use MDCChipField, the material design component for Swift. I am implementing the 'input chip' type and am able to add the entered text as a chip with

let mdcSearchField = MDCSearchField()
mdcSearchField.addChip(chipView)

When the chips overflow in MDCChipField, they get added to next row. How can i set the scrollable direction to horizontal instead of vertical?

In the link, https://material.io/design/components/chips.html#input-chips, The placement section explains

Input chips can be integrated with other components. They can appear:

 - Inline with the text input cursor in a field
 - In a stacked list
 - In a horizontally scrollable list

How do i do a a horizontally scrollable list in code?

Thanks.

anoo_radha
  • 812
  • 1
  • 15
  • 34

1 Answers1

1

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
        }
    }