Dropdown list in swift

2019-01-30 03:35发布

I am working on an iPhone app that has a filter list (dropdown list) under the navigation bar that appears when I click on the bar button. Please suggest me how can I do it.

enter image description here

2条回答
乱世女痞
2楼-- · 2019-01-30 04:16

There are a number ways to do it, my suggestions would be something similar to as follows:

When you initialise the view controller, your dropdown view is offset and hidden behind the navigation bar. Do this either with Layout Constraints or using the view's frame, depending on your preferred set up.

var isAnimating: Bool = false
var dropDownViewIsDisplayed: Bool = false

func viewDidLoad() {
    super.viewDidLoad()
    let height: CGFloat = self.dropDownView.frame.size.height
    let width: CGFloat = self.dropDownView.frame.size.width
    self.dropDownView.frame = CGRectMake(0, -height, width, height)
    self.dropDownViewIsDisplayed = false
}

Then link up an action to the BarButtonItem that, when pressed, displays the view if hidden or hides if visible using an animation.

@IBAction func barButtonItemPressed(sender: UIBarButtonItem?) {
    if (self.dropDownViewIsDisplayed) {
        self.hideDropDownView()
    } else {
        self.showDropDownView()
    }
}

func hideDropDownView() {
     var frame: CGRect = self.dropDownView.frame
     frame.origin.y = -frame.size.height
     self.animateDropDownToFrame(frame) {
         self.dropDownViewIsDisplayed = false
     }
}

func showDropDownView() {
    CGRect frame = self.dropDownView.frame
    frame.origin.y = self.navigationBar.frame.size.height
    self.animateDropDownToFrame(frame) {
        self.dropDownViewIsDisplayed = true
    }
}

func animateDropDownToFrame(frame: CGRect, completion:() -> Void) {
    if (!self.animating) {
        self.animating = true
        UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
            self.dropDownView.frame = frame
            }, completion: (completed: Bool) -> Void in {
                self.animating = false
                if (completed) {
                     completion()
                }
            })
    }
}

All that is left for you is to define your dropDownView and link it up correctly.

I hope that helps, please comment if there is anything you don't understand

查看更多
smile是对你的礼貌
3楼-- · 2019-01-30 04:16

To use Drop down List with custom View and with Tableview use the below link https://github.com/lminhtm/LMDropdownView

查看更多
登录 后发表回答