自定义带DropDownTable的TextField(UI部分)

这个自定义控件完全抄袭于GitHub.com上的一个项目,当做新手打字学习篇。

思路

(1),在TextField的下面创建一个UITableView,当在TextField输入文字的时候弹出这个table。

    为了让table浮在所有view的上面,需要调用superview.bringSubviewToFront();

  

var dropTable:UITableView!

dropTable = UITableView()


superview!.addSubview(dropTable) superview!.bringSubviewToFront(dropTable)

由于需要用到superview,不能允许在viewDidLoad中直接使用到superview.

在初始化的时候给TextFiled增加一个编辑事件,侦听用户输入情况,当用户输入文字的时候弹出来

func setupTextField(){
         addTarget(self, action: "editingChanged:",       forControlEvents:.EditingChanged)
    }

 func editingChanged(textField: UITextField) {
        if textField.text!.characters.count > 0 {
            setupTableView()
           // self.tableViewAppearanceChange(true)
        } else {
            if let dropDownTableView = dropTable {
              //  self.tableViewAppearanceChange(false)
            }
        }
    }

(2)设置约束使tableview的宽度正好跟TextFiled的宽度一致

 dropTable.translatesAutoresizingMaskIntoConstraints = false
            
            let leftConstraint = NSLayoutConstraint(item: dropTable, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0)
            let rightConstraint =  NSLayoutConstraint(item: dropTable, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0)
            heightConstraint = NSLayoutConstraint(item: dropTable, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: dropDownTableViewHeight)
            let topConstraint = NSLayoutConstraint(item: dropTable, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 1)
            
            NSLayoutConstraint.activateConstraints([leftConstraint, rightConstraint, heightConstraint, topConstraint])

 当用户点击除了tableview以外的地方,需要把tableview收起来。方法是给superview注册一个点击事件,判断点击区域

  let tapGesture = UITapGestureRecognizer(target: self, action: "tapped:")
 tapGesture.numberOfTapsRequired = 1
 tapGesture.cancelsTouchesInView = false
 superview!.addGestureRecognizer(tapGesture)


func tapped(gesture: UIGestureRecognizer) {
        let location = gesture.locationInView(superview)
        if !CGRectContainsPoint(dropTable.frame, location) {
            if let dropTable = dropTable {
                
                dropTable.hidden = true
                //self.tableViewAppearanceChange(false)
            }
} }

posted @ 2016-01-25 15:35  mogul  阅读(316)  评论(0编辑  收藏  举报