【问题标题】:Place CALayer at very bottom of layer stack of UIButton将 CALayer 放在 UIButton 层堆栈的最底部
【发布时间】:2014-08-04 21:41:53
【问题描述】:

这看起来很简单——也许你能帮我找到解决办法?

我为 UIButton 编写了自定义阴影。我试图将它放在 UIButton 层堆栈的最低索引处。不幸的是,它没有被放置在 UIButton 的其余部分下方。

代码:

//UIButton type custom
alarmSetterButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"rootSchedulerButton"];

//Scaling
float delta = 2.4f;
if (IS_IPHONE_5) delta = 2.0f;

[alarmSetterButton setFrame:CGRectMake(0.0f, 0.0f, (img.size.width/delta), (img.size.height/delta))];
[alarmSetterButton setBackgroundImage:img forState:UIControlStateNormal];
[alarmSetterButton setTitle:@"" forState:UIControlStateNormal];
[alarmSetterButton addTarget:self action:@selector(setSecondaryView:) forControlEvents:UIControlEventTouchUpInside];

//the colors for the gradient
UIColor *high = [UIColor colorWithWhite:0.0f alpha:1.0f];
UIColor *low = [UIColor colorWithWhite:0.0f alpha:0.0f];

//The gradient, simply enough.  It is a rectangle
CAGradientLayer * gradient = [CAGradientLayer layer];
[gradient setFrame:[b bounds]];
[gradient setColors:[NSArray arrayWithObjects:(id)[high CGColor], (id)[low CGColor], nil]];
[gradient setAnchorPoint:CGPointMake(0.5f, 0.0f)];
[gradient setTransform:CATransform3DMakeRotation(315.0 / 180.0 * M_PI, 0.0, 0.0, 1.0)];

// What needs altered
[alarmSetterButton.layer insertSublayer:gradient below:alarmSetterButton.layer];

【问题讨论】:

  • 您正试图将图层放置在自身下方,在自身之上。我的意思是alarmSetterButton.layer 不包含自身。
  • 这个怎么样? [alarmSetterButton.layer insertSublayer:gradient below:[alarmSetterButton.layer.subviews objectAtIndex:0];
  • 添加图层时会发生什么?结果如何?
  • @EDUsta 好主意 - 不幸的是它也不起作用。
  • @Milo - 渐变放置在背景图像的顶部。

标签: ios objective-c uibutton calayer


【解决方案1】:

我找到了解决方案。我没有使用 UIButton 的 setBackroundImage:forState: 方法,而是编写了一个新的 CALayer 来包含图像的内容。

感谢您的帮助。

:)

【讨论】:

    【解决方案2】:

    试试这个,它将层放置在堆栈中的零位置,即底部。

    [alarmSetterButton.layer insertSublayer:gradient atIndex:0];
    

    【讨论】:

    • 不幸的是结果相同
    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多