【问题标题】:Subview appears underneath superviews layer.border?子视图出现在superviews layer.border下面?
【发布时间】:2013-03-07 14:38:00
【问题描述】:

我有一个UIView,我用以下方式定义它的边界:

self.layer.borderColor = [UIColor blackColor].CGColor;
self.layer.borderWidth = 3;

我在这个UIView 上附加了一个子视图,当我将子视图移到边框上时,它会移到它的下方。这是预期的行为吗?有没有办法让子视图在它上面?

【问题讨论】:

  • 苹果文档说The border is drawn inset from the receiver’s bounds by the value specified in this property. It is composited above the receiver’s contents and sublayers 所以边框在你所有层的顶部(包括你的子层)
  • 好提示@郭陆川!也许使用背景图像覆盖另一个 UIView
  • @aăâ 是的,你是对的,让背景视图假装边框可以处理。也许其他人有一个完美的方法来处理它。而且我们也想过有没有完美的方法

标签: iphone ios cocoa-touch uiview calayer


【解决方案1】:

根据Apple specification:It is composited above the receiver’s contents and sublayers.

因此,边框将始终位于所有子视图的上方,即使您将子视图置于最前面等等。

所以我制作了一个背景视图来伪造边框。

例如:

UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
backgroundView.backgroundColor = [UIColor blackColor];
backgroundView.clipsToBounds = NO;

UIView *bView = [[UIView alloc] initWithFrame:CGRectInset(backgroundView.bounds, 3, 3)];
bView.backgroundColor = [UIColor redColor];

UIView *cView = [[UIView alloc] initWithFrame:CGRectMake(-50, -50, 100, 100)];
cView.backgroundColor = [UIColor yellowColor];
[bView addSubview:cView];

[backgroundView addSubview:bView];

[self.window addSubview:backgroundView];

以及效果:

【讨论】:

  • 我认为也可以制作一个包含边框视图的视图,以及假设作为子视图在其之上的视图,然后确保首先附加边框视图。
  • @StackOverFlowRider 是的,你可以创建一个 CustomView ,它的 .viewborderCustomView 有一个 UIView 属性可以命名为 yourViewyourView 是您真正有用的视图,yourViewsubviewCustomView.view
  • 谢谢你的回答。
  • 确保将子视图的 #exclusiveTouch# 和 #userInteractionEnabled# 属性设置为 NO 以将触摸事件传递给按钮本身 (interactivelogic.net/wp/2011/07/…)
  • 这样你将无法设置清晰的背景
【解决方案2】:

根据您的视图结构,将子视图添加到主视图的父级 可能更容易。然后它可以与主视图重叠,并按照您的要求覆盖边框。

【讨论】:

    【解决方案3】:

    您是否尝试将超级视图的“clipsToBounds”属性设置为“是”?出于性能原因,默认情况下将其设置为 NO,但将其设置为 yes 可能会给您想要的效果。

    【讨论】:

    • 我需要将它设置为 no,因为这个视图超出了它的超级视图边界。
    【解决方案4】:

    在适合您的特定位置插入图层:

    self.layer.insertSublayer(sublayer, at: 0)
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多