隐藏视图后隐藏 UIButton(以编程方式添加)

Hiding UIButton(which added programatically) once view is hidden

目标: 隐藏视图后隐藏 UIButton(带图像)。

我有一个布局,当用户在屏幕上点击 (UITapGestureRecognizer) 时,可以隐藏地图视图。发生这种情况时,我想隐藏“关注用户按钮”三角形。目前我做不到。

我尝试过的:(来自多个 google/SO 帖子)

1)

followUserButton.removeFromSuperview()
followUserButton.widthAnchor.constraint(equalToConstant: 150).isActive = true
followUserButton.heightAnchor.constraint(equalToConstant: 150).isActive = true
followUserButton.setImage(image:nil for: .normal)

我尝试的最后一个基本上只是使图像变黑(以融入背景)。这看起来确实成功了,但是(参见 gif 图像),出于某种原因,第一次单击仍会显示按钮(非常亮 black/grey - 在图像的底部中间)。再次点击,地图视图出现,然后再次点击,地图视图终于消失

followUserButton.tintColor = .black
  1. followUserButton.isHidden = 真

这就是我以编程方式添加按钮的方式

  var followUserImage: UIImage!
  var followUserButton: UIButton!

  override func viewDidLoad() {    
    setupFollowUserButton()
  }

  func setupFollowUserButton() {
          addFollowUserButton()
          self.view.addSubview(followUserButton)
          constraintFollowUserButton()
      }      

  func hideFollowUserButton() {
    if vcTrainMapView.isHidden {
      if followUserButton != nil {
        //  followUserButton.removeFromSuperview()
        //  followUserButton.tintColor = .black
        followUserButton.isHidden = true
      }
    } else if followUserButton != nil {
      followUserButton.tintColor = .lightGray
    }
  }

    func addFollowUserButton() {
        followUserButton = UIButton(type: UIButton.ButtonType.custom)
        followUserImage = UIImage(named: "follow_user_high")
        followUserButton.setImage(followUserImage, for:.selected)
        followUserImage = (UIImage(named: "follow_user"))
        followUserButton.setImage(followUserImage, for: .normal)
        followUserButton.tintColor = .lightGray
        followUserButton.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
      }
    
      @objc private func buttonAction(_ sender: UIButton) {
        self.followUserStatus = !self.followUserStatus
        sender.isSelected.toggle()
      }
      
      func constraintFollowUserButton() {
        followUserButton.translatesAutoresizingMaskIntoConstraints = false
        followUserButton.bottomAnchor.constraint(equalTo: vcTrainMapView.bottomAnchor, constant: -10).isActive = true
        followUserButton.leadingAnchor.constraint(equalTo: vcTrainMapView.leadingAnchor, constant: 10).isActive = true
        followUserButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
        followUserButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
      }

这就是我在上面的#3 中取得的成就。 (gif 中的按钮很亮)

如果您要在显示详细信息视图(您的地图视图)的同时隐藏和显示一个按钮,并且您正在显示该按钮以使其看起来像是在该视图中,您可以只需将按钮直接添加到该视图而不是视图控制器主视图。

当然,您仍然可以从视图控制器控制按钮的操作,但如果将其添加到地图视图中,则在隐藏地图视图时按钮将被隐藏。