斯威夫特:圆形视图与内部阴影

时间:2016-01-12 19:34:41

标签: swift uiview border

我正在尝试在这里实现解决方案(我转换为Swift):How to create rounded UITextField with inner shadow

我的代码如下:

    mobileInputView.layer.cornerRadius = 5.0;

    let shadowLayer = CAShapeLayer()
    shadowLayer.frame = mobileInputView.bounds;

    // Standard shadow stuff
    shadowLayer.shadowColor = UIColor(white: 0, alpha: 1).CGColor
    shadowLayer.shadowOffset = CGSizeMake(0.0, 0.0)
    shadowLayer.shadowOpacity = 1.0
    shadowLayer.shadowRadius = 4

    // Causes the inner region in this example to NOT be filled.
    shadowLayer.fillRule = kCAFillRuleEvenOdd

    // Create the larger rectangle path.
    let path = CGPathCreateMutable();

    CGPathAddRect(path, nil, CGRectInset(mobileInputView.bounds, -42, -42));

    // Add the inner path so it's subtracted from the outer path.
    // someInnerPath could be a simple bounds rect, or maybe
    // a rounded one for some extra fanciness.
    let someInnerPath = UIBezierPath(roundedRect: mobileInputView.bounds, cornerRadius:5.0).CGPath
    CGPathAddPath(path, nil, someInnerPath)
    CGPathCloseSubpath(path);

    shadowLayer.path = path

    //CGPathRelease(path);

    mobileInputView.layer.addSublayer(shadowLayer)
    //[[_textField layer] addSublayer:shadowLayer];

    let maskLayer = CAShapeLayer()
    maskLayer.path = someInnerPath
    shadowLayer.mask = maskLayer

但是这种观点最终会像这样出现:

Wrong size border!

组件的宽度是正确的,我可以键入到屏幕的边缘,它只是出现不合适大小的边框。如果我设置了视图的背景颜色,我可以看到视图本身的大小正确。

如果我尝试使用.frame而不是.bounds,我会得到相同的结果。

1 个答案:

答案 0 :(得分:0)

实现这一目标的一种更简单的方法是直接修改UITextField而不使用UIView和标签:

    let label = UILabel(frame: CGRectMake(1, 1, 125, 25))
    label.text = "Mobile number:"
    label.textAlignment = NSTextAlignment.Right

    mobileNumber.leftView = label
    mobileNumber.leftViewMode = UITextFieldViewMode.Always

    mobileNumber.borderStyle = UITextBorderStyle.Bezel;
    mobileNumber.layer.borderWidth = 1.0
    mobileNumber.layer.borderColor = UIColor.grayColor().CGColor
    mobileNumber.layer.cornerRadius = 5.0