这有点骇人听闻,但这可以解决问题,并且它可以与 UIView 子类的各种其他 UI 控件一起使用。这假设你有自己的子类DialogViewController(我的有很多方便省时的东西,我所有的视图子类我的 DVC 来工作)。
protected void ForAllSubviewUIControlsOfType<TUIType>(Action<TUIType, int> actionToPerform) where TUIType : UIView
{
processSubviewUIControlsOfType<TUIType>(this.View.Subviews, actionToPerform, 0);
}
private void processSubviewUIControlsOfType<TUIType>(UIView[] views, Action<TUIType, int> actionToPerform, int depth) where TUIType : UIView
{
if (views == null)
return;
if (actionToPerform == null)
return;
foreach (UIView view in views)
{
if (view.GetType () == typeof(TUIType))
{
actionToPerform((TUIType)view, depth);
}
if (view.Subviews != null)
{
foreach (UIView subview in view.Subviews)
{
processSubviewUIControlsOfType<TUIType>(view.Subviews, actionToPerform, depth + 1);
}
}
}
}
要解决原始问题并更改部分中所有标签的文本颜色,您需要执行以下操作:
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
ForAllSubviewUIControlsOfType<UILabel>((label, depth) => {
if ( /*label.Superview is UIView && label.Superview.Superview is UITableView*/ depth == 1 )
{
label.TextColor = UIColor.Black;
}
});
}
在我决定返回 int depth 计数以查看它是否在视图中之前,注释掉的部分是确定标签是否存在于部分中的部分。
编辑:似乎这不是完美的解决方案……深度计数因这些元素而异。我必须在接下来的一两天内找到更好的办法。