【问题标题】:How to access the controls on UIView which is added to a UIScrollView如何访问添加到 UIScrollView 的 UIView 上的控件
【发布时间】:2012-09-26 11:08:27
【问题描述】:

我在情节提要中有一个 UIViewController,其中包含一个滚动视图。

我想在上面放两个 UIImageView 和一些 UILabel。

我的想法是:创建一个 .xib 文件。在上面放一个 UIView,然后在这个 UIView 上设置我的 UIImageview 和标签。

最后将我的 UIView 这是一个 .xib 文件添加到我的 UIScrollView 中,如下所示:

 NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"OfferView" owner:self options:nil];
UIView *newPageView = [views lastObject];
self.newPageView.contentMode = UIViewContentModeScaleAspectFill;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];

现在我想在我的 UIViewController 中以编程方式为 UIView 上的控件设置文本和图像。我尝试了这个,但它不起作用:

OfferUIView *offer2 = [[OfferUIView alloc] init];;
offer2.labelCompany.text = @"some text";

我也在ViewController的接口中定义了OfferUIView,然后同步,但也没有用:

@property (nonatomic, assign) OfferUIView *offerView;

你能帮帮我吗?

【问题讨论】:

  • 为什么不在情节提要中布局内容,以便您可以轻松地将视图连接到视图控制器中的插座?
  • 因为我想在我的scrollView中添加一个UIView,我无法在storyboard中单独创建一个UIView,所以我使用.xib文件。如果您认为这不是一个好方法,请为我​​写一个完整的答案,我会看看它。

标签: iphone objective-c ios xcode


【解决方案1】:

当您将笔尖加载到您的offerView 属性时,为您的OfferView 设置指针

NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"OfferView" owner:self options:nil];
self.offerView = [views lastObject];
self.offerView.contentMode = UIViewContentModeScaleAspectFill;
self.offerView.frame = frame;
[self.scrollView addSubview:self.offerView];
[self.pageViews replaceObjectAtIndex:page withObject:self.offerView];

当你想改变它时:

self.offerView.labelCompany.text = @"some text";

【讨论】:

  • 我试过这个,但它不起作用,顺便说一句,我找到了另一个使用 tag 的解决方案。您确定您的解决方案有效吗?
  • 是的,应该。您确定要在添加视图后更改文本吗?
  • 谢谢,现在成功了,你认为这个想法更好还是使用标签?请告诉我你的理由。
  • 由于viewWithTag: 对视图及其所有子视图执行搜索,它比仅使用指针更复杂(需要更多计算)。
【解决方案2】:

OfferUiView 必须为“initWithFrame”,因为它是“UIView”类的任何视图的必需方法,或者为此视图设置一个框架。由于您已将 UIView 子类化,因此将 initWithFrame 作为其构造函数进一步,因为你已经以编程方式分配了 OfferUIView 你必须将此视图添加到你的当前视图中,即 [self.view addSubView:offer2];

【讨论】:

    【解决方案3】:

    你可以为tag设置一个唯一的标签,你可以像这样在parentView中搜索标签:

    UILabel *theLabel = (UILabel *)[parentView viewWithTag: 10321];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2011-05-27
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多