Swift: How can I detect elements inside of a UIVie

2019-07-13 05:30发布

I am wondering two things (I am a Swift beginner):

1) Is there a way to detect or target elements (children) are inside a give UIView.

2) Are the elements inside the UIView stored in an array?

As an example let say I have a UIView called parentView and it has inside an ImageView (called imageChildre) and a LabelView (called labelChildre)

How can I target the children?

Thanks for your help

标签: ios swift uiview
2条回答
闹够了就滚
2楼-- · 2019-07-13 06:30
  1. Something like this? You can change condition accordingly.

    for subview in parentView.subviews
    {
        if let item = subview as? UIImageView
        {
            //this is image view
        }
    }
    
  2. parentView.subviews is an array of views inside parentView

查看更多
劫难
3楼-- · 2019-07-13 06:31

You asked:

1) Is there a way to detect or target elements (children) are inside a give UIView.

Generally, you hook up outlets to those subviews in Interface Builder when you first designed the view.

Or if doing it programmatically, you'd keep a reference to the various subviews of the view as you programmatically added them to the view.

We'd need to know how you built this view and its subviews to advise further.

2) Are the elements inside the UIView stored in an array?

Yes, every UIView has a property called subviews which is all of those subviews of the view. But you wouldn't generally use this to access the subviews, but rather use the technique outlined in answer to your first question.

查看更多
登录 后发表回答