无法从 Controller 设置 UIView 背景颜色

Posted

技术标签:

【中文标题】无法从 Controller 设置 UIView 背景颜色【英文标题】:Unable to set UIView background color from Controller 【发布时间】:2013-08-25 17:44:07 【问题描述】:

我有一个包含多个 UIView 的应用(XCode 4.6、Storyboards、ios 6.2 和 ARC):

每个 UIView 都有 XCode 中定义的背景颜色。我希望能够根据用户选择的方案更改背景颜色(当前为浅黄色)。在 CalendarViewController 的 -viewDidLoad 方法中,我有这样的代码:

self.leftGrid.backgroundColor = [UIColor blueColor];
[self.leftGrid setNeedsDisplay];

这是 CalendarViewController 的 .h 文件中的代码:

//  these all all UIViews
@class SubViewGrid;
@class SubViewData;
@class CalendarView;
@class TopGrid;
@class LeftGrid;

@interface CalendarViewController : UIViewController <UIScrollViewDelegate>  



//  UIScrollView properties
@property (nonatomic, weak) IBOutlet UIScrollView *schedScrollView;
@property (strong, nonatomic) IBOutlet UIView *topGrid;
@property (strong, nonatomic) IBOutlet UIView *leftGrid;
@property (strong, nonatomic) IBOutlet UIScrollView *topGridSV;
@property (strong, nonatomic) IBOutlet UIScrollView *leftGridSV;

问题是:什么都没有发生!我究竟做错了什么? (我查看了 SO 和 Google 搜索,但没有发现任何相关内容)

【问题讨论】:

leftGrid 是否标记为 IBOutlet,并连接到您在 IB 中的班级? 加载视图时会发生这种情况吗? F.e 在 vi​​ewDidLoad:?不在 init 方法中 我编辑了这个问题...我添加了@class 行以消除我很久以前遇到的错误,但不确定它们除了防止循环引用之外还能做什么... 您是否在 viewDidLoad 中检查了 self.leftGrid 的 nil ?也许xib的所有者设置不正确?或者 IB 中的视图与其所有者字段之间的联系? 请重新写下您的评论作为答案...这不完全是,但是有一个检查是否设置了一个标志来指示请求哪种配色方案,并且 是零。感谢您的帮助,我很感激! 【参考方案1】:

viewDidLoad 中似乎是self.leftGrid == nil。也许 xib 的所有者设置不正确。或者 IB 中的视图与其所有者字段之间的连接。

【讨论】:

以上是关于无法从 Controller 设置 UIView 背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

无法更改 IBOutlet 属性的框架

UIView.animate with repeat 选项在新的 View Controller 出现时停止

自定义 UIView 在 View Controller 中被解包为 nil

为啥我在 UIScrollView 中的 UIView 不滚动?

在 UIView 和 UIViewController 之间传递数据

如何获取嵌套在 UIView 中的 UIView 框架 - Objective C