0
votes

I am trying to implement the solution here (which I converted to Swift): How to create rounded UITextField with inner shadow

My code is as follows:

    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

But the view ends up coming out like this:

Wrong size border!

The width of the component is correct, I can type until the edge of the screen, it's just the border that comes out a bad size. If I set the background colour of the view I can see the view itself is being sized correctly.

If I try using .frame instead of .bounds I get the same result.

1

1 Answers

0
votes

A much simpler way to achieve this is to modify the UITextField directly without have the outlining UIView and the label:

    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