UISegmentedControl not intractable when there is nothing above it

OK – I got your code to run.

The problem is that your Segmented Control is extending outside the bounds of the table header view.

I think it would make much more sense to keep all of your UI elements that are part of the “stretchy header” inside the header class, so this is not how I would recommend doing this, but this should give you back your segmented control interaction:

In your SecondaryStretchyTableHeaderView class, add this var / property:

weak var segControl: UISegmentedControl?

In addTitle() in your TertiaryProfileScroll class, add this:

    // your existing code

    // add this
    if let v = tableView.tableHeaderView as? SecondaryStretchyTableHeaderView {
        // give our custom header view a reference to the segemented control
        v.segControl = segmentedControl

Back in your SecondaryStretchyTableHeaderView class, add this func:

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    guard isUserInteractionEnabled,
          alpha >= 0.01,
          let sc = segControl
    else { return nil }

    // if we tap outside the bounds,
    //  but on the segmented control
    //  return the segmented control
    let convertedPoint = sc.convert(point, from: self)
    if let v = sc.hitTest(convertedPoint, with: event) {
        return v
    guard self.point(inside: point, with: event) else { return nil }
    return self

That will allow you to interact with the segmented control, even when it is outside the bounds of the table header view.

As a side note, it appears you’re setting .layer.zPosition where you don’t need to. In cellForRowAt I commented out these lines:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    cell?.textLabel?.text = String(indexPath.row)
    //cell?.layer.zPosition = -1000
    return cell!

and also commented out this line (at the end of addTitle()):

//segmentedControl.layer.zPosition = 1000

and I don’t see any difference.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top