Раскрывающееся меню UIView, открытое с помощью кнопки в UITableviewCell, не активируется за пределами границ ячейки - PullRequest
0 голосов
/ 09 февраля 2019

Я пытаюсь заставить кнопку открыть выпадающее меню в стиле UIView внутри пользовательского UITableViewCell.И это действительно открывает UIView, содержащий другие кнопки.Отлично.Однако единственная кликабельная часть - это крошечная цифра «1» внутри UITableViewCell.Остальная часть выпадающего меню не активна, и вы можете щелкнуть по нему в ячейку ниже.Как сделать так, чтобы кнопка в пользовательском UITableViewCell открывала UIView с выпадающим меню и чтобы каждая кнопка внутри UIView была интерактивной?

Вот как это выглядит сейчас.screen 1 screen 2 screen 3

//The button inside the UITableViewCell:


class PriorityButton: UIButton, DropDownDelegate {
var dropDownView = DropDownView()

var height = NSLayoutConstraint()
var isOpen = false

override init(frame: CGRect) {
    super.init(frame: frame)

    dropDownView = DropDownView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    dropDownView.delegate = self
    dropDownView.translatesAutoresizingMaskIntoConstraints = false

    //        button.setImage(UIImage(named: "UnChecked"), for: .normal)
    //        button.setImage(UIImage(named: "Checked"), for: .selected)
    self.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    self.setTitleColor(.black, for: .normal)
    self.backgroundColor = UIColor.white
    self.layer.borderWidth = 2
    self.layer.borderColor = UIColor.black.cgColor
    self.titleLabel?.font = UIFont.init(name: "Avenir Next", size: 24)
}

override func didMoveToSuperview() {
    self.superview?.addSubview(dropDownView)
    self.superview?.bringSubviewToFront(dropDownView)

    dropDownView.topAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    dropDownView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    dropDownView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
    height = dropDownView.heightAnchor.constraint(equalToConstant: 0)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if isOpen == false {

        isOpen = true

        NSLayoutConstraint.deactivate([self.height])

        if self.dropDownView.priorityTableView.contentSize.height > 300 {
            self.height.constant = 300
        } else {
            self.height.constant = self.dropDownView.priorityTableView.contentSize.height
        }


        NSLayoutConstraint.activate([self.height])

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
            self.dropDownView.layoutIfNeeded()
            self.dropDownView.center.y += self.dropDownView.frame.height / 2
        }, completion: nil)
    } else {
        isOpen = false

        NSLayoutConstraint.deactivate([self.height])
        self.height.constant = 0
        NSLayoutConstraint.activate([self.height])

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
            self.dropDownView.center.y -= self.dropDownView.frame.height / 2
            self.dropDownView.layoutIfNeeded()
        }, completion: nil)
    }
}

func dismissDropDown() {
    isOpen = false

    NSLayoutConstraint.deactivate([self.height])
    self.height.constant = 0
    NSLayoutConstraint.activate([self.height])

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
        self.dropDownView.center.y -= self.dropDownView.frame.height / 2
        self.dropDownView.layoutIfNeeded()
    }, completion: nil)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func dropDownPressed(string: String) {
    self.setTitle(string, for: .normal)
    self.dismissDropDown()
}
}

// Представление выпадающего меню

class DropDownView: UIView, UITableViewDelegate, UITableViewDataSource {

let priorityLevel = ["1", "2", "3", "4", "5"]
var priorityTableView = UITableView()
var delegate: DropDownDelegate!

override init(frame: CGRect) {
    super.init(frame: frame)

    self.backgroundColor = .white

    priorityTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
    priorityTableView.backgroundColor = .white
    priorityTableView.delegate = self
    priorityTableView.dataSource = self
    priorityTableView.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(priorityTableView)

    priorityTableView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
    priorityTableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    priorityTableView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    priorityTableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return priorityLevel.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
    cell.textLabel?.text = priorityLevel[indexPath.row]
    cell.backgroundColor = .white
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("test")
}
}

Ожидаемые результаты: я хочу нажать на кнопку «1» в пользовательскомUITableViewCell и показывает раскрывающееся меню UIView и может нажимать на кнопки, содержащиеся в раскрывающемся меню.

1 Ответ

0 голосов
/ 10 февраля 2019

Мне кажется, проблема в том, что раскрывающийся список добавляется в супер-представление ячейки (он же tableView), а делегат раскрывающегося списка назначается самой ячейке, поэтому он не будет реагировать на распознаватель жестов касания, посколькутабличное представление не является его делегатом, и касание должно происходить в ячейке, попробуйте добавить его во вспомогательное представление ячейки вместо superView, возможно, это сработает.Удачи ?

...