【问题标题】:Change UIView (inside nib) background from other viewcontroller从其他视图控制器更改 UIView(笔尖内)背景
【发布时间】:2013-05-31 15:48:48
【问题描述】:

有人知道如何从另一个视图控制器更改笔尖内的视图吗?我有一个从 nib 文件中的视图到视图类文件的出口,我有 @synthesize 视图类 .m 文件。然后我#import "InfoView.h"(这是视图类)视图到视图控制器,最后我:

    InfoView *infoView; 
    if (infoView == nil) 
    { 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"infoView" owner:self options:nil]; 
    infoView = [nib objectAtIndex:0]; 
    } 

infoView.contentView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];" 

但我无法改变背景。

以前有没有人尝试过这样的事情? 感谢您的任何意见!

编辑: 已解决 UIColor 问题,但这不是问题。

【问题讨论】:

  • 确保您在自定义视图中正确链接了插座,并确保您已在 xib 文件中指定自定义视图的类
  • @danypata 是的,已经这样做了
  • @PaperThick 使用 colorWithRed 方法时需要除以 255.0f

标签: iphone ios uiview uiviewcontroller


【解决方案1】:

试试这段代码,我已经为你制作了演示应用程序。 创建文件CustomView.h

#import <UIKit/UIKit.h>

@interface CustomView : UIView

@property (nonatomic, strong) IBOutlet UILabel *titleLbl;

@end

CustomView.m。如果您使用的是 XIB

#import "CustomView.h"

@implementation CustomView

@synthesize titleLbl = _titleLbl;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super initWithCoder:aDecoder])
    {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
        UIView *theEditView = [nibObjects objectAtIndex:0];
        theEditView.frame = self.bounds;
        [self addSubview: theEditView];
        theEditView = nil;
    }


    return self;
}

fileOwnerCustomView.XIB 设置为CustomView。并连接插座。 无论您想在哪里使用CustomView,都可以在XIB 中使用UIView 对象,并将UIView 类重命名为CustomView。在您的.h 文件中创建一个IBOutlet,并将其与XIB 中的CustomView 对象连接。 现在这样做:

self.customViewObj.backgroundColor = [UIColor redColor];
self.customViewObj.titleLbl.text = @"Prateek";

在您的情况下,您的 customview 对象未创建。如果你打印你的对象,它会告诉你nil

【讨论】:

    【解决方案2】:

    您错误地使用了-colorWithRed:green:blue:alpha。他们期望一个介于 0 和 1 之间的浮点值。您需要这样做:

    infoView.contentView.backgroundColor = [UIColor colorWithRed:50.0/255.0 green:50.0/255.0 blue:50.0/255.0 alpha:1];" 
    

    【讨论】:

    • 感谢您的回答,但现在我使用标签进行了测试,但无法从视图控制器更改其上的文本,所以它一定是链接问题
    • 你确定 infoView 是 != nil 吗?您在哪里将其添加为子视图?
    【解决方案3】:

    如果您尝试更改背景颜色.. 则执行以下操作:

    infoView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];
    

    【讨论】:

      猜你喜欢
      • 2011-11-15
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2013-04-11
      • 2013-09-18
      • 1970-01-01
      • 2015-09-06
      相关资源
      最近更新 更多