Swift - getting subpoints

In my application, I add labels to the view, and then try to clear certain labels from the view when I click the button and start an error when trying to get subheadings:

class FirstViewController: UIViewController { @IBAction func btnAddTask_Click(sender: UIButton){ var subViews = self.subviews.copy() } } 

I get an error message:

"FirstViewController" does not have a member named "subviews"

How can I get the subitems of the current view?

+7
source share
3 answers

UIViewController does not have subviews property. It has a view property that has the subviews property:

 for subview in self.view.subviews { // Manipulate the view } 

But usually this is not a good idea. Instead, you should put the desired labels in the IBOutletCollection and IBOutletCollection over them. Otherwise, you are very attached to the exact set of subzones (which may change).

To create an IBOutletCollection , select all the labels you want in IB and drag them to the source code. He should ask if you want to create an array of collections. (Note that there are no promises in the order of this array.)

+12
source

To search for all subzones from your view, you can use this code:

 for subview in self.view.subviews { // Use your subview as you want } 

But to use it, you must determine what you need. You can mark any item that you create with a special identifier:

 myButton.restorationIdentifier = "mySpecialButton"; 

And after that you can find that your element uses this structure:

 for view in view.subviews { if (view.restorationIdentifier == "mySpecialButton") { print("I FIND IT"); view.removeFromSuperview(); } } 

:)

+9
source

Hacky Elegance:

  1. Get click position.
  2. Get view with hitTest.
  3. Distinguish a view with an accessibilityIdentifier.

accessibilityIdentifier is designed for developers and is designed to automate the user interface.

Swift 4

 @objc func handleTap(_ gestureRecognizer: UITapGestureRecognizer) { let positionInView = gestureRecognizer.location(in: view) let hitTestView = view?.hitTest(positionInView, with: nil) print("hitTestView: \(hitTestView?.accessibilityIdentifier)") } 
0
source

Source: https://habr.com/ru/post/975968/


All Articles