随处访问 UIWindow 下添加的 UIImageView
在我的应用程序启动委托中,我有以下代码:
[window addSubview:[myTabBarController view]];
UIImageView *banner =
[[[UIImageView alloc] initWithFrame:CGRectMake(0,381,320,50)] autorelease];
banner.backgroundColor = [UIColor redColor];
[window addSubview:banner];
[window makeKeyAndVisible];
这按预期工作。选项卡栏可见,我的 UIImageView 也可见。
我需要在应用程序中的所有位置修改 UIImageView
(我有 TabBarController
、NavigationController
、UITableView
等)
例如,我想在单击 UITableCell
时更改背景颜色。
我尝试了一切:self.window.view.subviews
,atObjectIndex
,似乎都没有获得当前的背景颜色。
In my app start delegate I have the following code:
[window addSubview:[myTabBarController view]];
UIImageView *banner =
[[[UIImageView alloc] initWithFrame:CGRectMake(0,381,320,50)] autorelease];
banner.backgroundColor = [UIColor redColor];
[window addSubview:banner];
[window makeKeyAndVisible];
This works as expected. The tab bar is visible and also my UIImageView
is visible.
I need to modify that UIImageView
everywhere in my app (I have the TabBarController
, a NavigationController
, UITableView
, etc)
For example, I want to change the background color when I click in a UITableCell
.
I tried everything: self.window.view.subviews
, atObjectIndex
, neither seems to get the current background color.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定要这样做吗?
通常最好安排您的应用程序,以便操作视图控制器的视图层次结构的唯一对象是该视图控制器。如果其他对象想要更改某些内容,它们要么更改数据模型,要么向视图控制器发送消息。因此,您可以为视图控制器提供一个“backgroundColor”属性,并且其设置器将更新适当的视图。通过视图控制器间接设置背景颜色可以更轻松地在将来更改视图层次结构,并且通常可以使事物更好地组织。
Are you sure you want to do that?
It's usually best to arrange your app so that the only object manipulating a view controller's view hierarchy is that view controller. If other objects want to change something, they either change the data model or send a message to the view controller. So, you might give your view controller a 'backgroundColor' property, and its setter would update the appropriate view. Setting the background color indirectly through the view controller makes it easier to make changes to your view hierarchy in the future and generally keeps things better organized.
首先,如果只是设置背景颜色,则不需要 UIImageView。一个 UIView 就足够了。
为了解决您的问题,您可以在 AppDelegate 中保留对要更改背景颜色的视图的引用。然后,您可以从应用程序中的任何位置访问 AppDelegate (以及对视图的引用),如下所示:
first you do not need an UIImageView if its just to set a background-color. A UIView is sufficient.
to solve your problem, you can keep a reference to the view who's background-color you want to change in you AppDelegate. you can then access you AppDelegate (and the the reference to your view) from anywhere in your app like so: