iOS使用阴影为UILabel添加底部边框

时间:2012-09-08 07:59:42

标签: ios uilabel calayer

我是否知道如何仅使用阴影向UILable添加底部边框? 没有顶部,左侧,右侧边界。

这不起作用。这是我尝试过的代码,但它没有用。

CALayer* layer = [titleLabel layer];
layer.frame = CGRectMake(-1, -1, titleLabel.frame.size.width, 1.0f);
layer.borderWidth=1;
[layer setBorderWidth:2.0f];
[layer setBorderColor:[UIColor blackColor].CGColor];
[layer setShadowOffset:CGSizeMake(-3.0, 3.0)];
[layer setShadowRadius:5.0];
[layer setShadowOpacity:5.0];

2 个答案:

答案 0 :(得分:24)

以这种方式测试:

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];

[lbl setText:@"Testo di prova..."];
[lbl setBackgroundColor:[UIColor clearColor]];
[[self view] addSubview:lbl];
[lbl sizeToFit];

CALayer* layer = [lbl layer];

CALayer *bottomBorder = [CALayer layer];
bottomBorder.borderColor = [UIColor darkGrayColor].CGColor;
bottomBorder.borderWidth = 1;
bottomBorder.frame = CGRectMake(-1, layer.frame.size.height-1, layer.frame.size.width, 1);
[bottomBorder setBorderColor:[UIColor blackColor].CGColor];
[layer addSublayer:bottomBorder];

我希望这有助于你

答案 1 :(得分:0)

只需发布此答案以供参考,因为用户已经得到答案, 在Swift中试用这段代码,让我知道它是怎么回事......

func buttomBorder(label: UILabel) -> UILabel {
    // For Buttom Border
    let frame = label.frame
    let bottomLayer = CALayer()
    bottomLayer.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width - 2, height: 1)
    bottomLayer.backgroundColor = UIColor.lightGray.cgColor
    label.layer.addSublayer(bottomLayer)
    //For Shadow
    label.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).CGColor
    label.layer.shadowOffset = CGSizeMake(0.0, 2.0)
    label.layer.shadowOpacity = 1.0
    label.layer.shadowRadius = 0.0
    label.layer.masksToBounds = false
    label.layer.cornerRadius = 4.0

    return label

}

功能调用:

 labelName = buttomBoder(label: labelName)