在开发过程中有没有办法仅仅识别不同的自定义视图?有没有什么技巧或窍门来区分它们?
我能想到的最接近的方法是在IB中设置背景颜色,然后在自定义视图的实现中删除背景。
边界矩形可能会很有用。您可以通过转到菜单栏并选择 编辑 > 画布 > 显示边界矩形 来打开它们。
这是一个例子。我有一个视图(一个 UICollectionViewCell
子类)在nib文件中进行布局。它有一个单行标签,一个两行标签和一个自定义子视图。该自定义子视图本身包含一个较小的自定义子视图。这是关闭边界矩形时的nib文件:
这是打开边界矩形时的同一nib文件:
这里是另一种建立在设置背景颜色的基础上的技术。此技术要求您的部署目标为 iOS 5.0 或更高版本。
像您所描述的那样,设置背景颜色以使视图在nib文件中可见:
然后切换到“Identity Inspector”并在“User Defined Runtime Attributes”部分中添加 backgroundColor
。将其设置为您想要视图在运行时具有的背景颜色。例如,如果您想要它在运行时为白色:
如果您想要背景颜色为透明,则可以将 backgroundColor
设置为不透明度为0的颜色,或者将其设置为“Nil”,而不是任何颜色:
在Interface Builder中设置背景颜色,但在代码中重新设置背景颜色的方法是一种简单而有效的技术。有两个改进点:
If you have multiple custom views on a single storyboard scene, you can save yourself from having to programmatically clear the background color for all of them individually by using IBOutletCollection
. So, in Interface Builder, give them all background colors and then add all of your custom views for a given scene to a collection. You then can set the background color for all of them in a single statement. So, for example, if you have a dozen controls on one scene all in a single IBOutletCollection
is named viewsCollection
:
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *viewsCollection;
you can clear the background color of all of them in a single statement:
[self.viewsCollection setValue:[UIColor clearColor] forKey:@"backgroundColor"];
You can also make the identification of your custom views in Interface Builder a little easier by setting the "Label" in the "Document" properties on the "Identity inspector":
Once you've done that, when you look at the document outline in the left side of the main panel, you'll see your labels show up:
Then, using the document outline makes it easier to identify your individual views in the scene. You can use a random label like I did here, or you could use the name of your custom view class, or whatever.