Auto Layout constraint on CALayer IOS

2019-01-16 22:17发布

Hi I am developing iPhone application in which I tried to set one side border for edittext. I did this in following way:

 int borderWidth = 1;
CALayer *leftBorder = [CALayer layer];

leftBorder.borderColor = [UIColor whiteColor].CGColor;
leftBorder.borderWidth = borderWidth;

leftBorder.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField
                              .frame.size.width, borderWidth);
[textField.layer addSublayer:leftBorder];

I put some constraints on my edittext in IB so that when I rotate my device it will adjust width of text field according to that. My problem is that adjusts the width of edittext not adjusting the width of CALayer which I set for my edit text. So I think I have to put some constraints for my CALayer item as well. But I dont know how to do that. ANy one knows about this? Need Help. Thank you.

7条回答
太酷不给撩
2楼-- · 2019-01-16 22:49

Checkout this solution. Use KVO, for the path "YourView.bounds" as given below.

self.addObserver(self, forKeyPath: "YourView.bounds", options: .New, context: nil)

Then handle it as given below.

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        if (keyPath == "YourView.bounds") {
            YourLayer.frame = YourView.bounds
            return
        }
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }

For more info, refer the following link.

https://theswiftdev.com/2015/03/28/auto-layout-with-layers/

查看更多
欢心
3楼-- · 2019-01-16 22:55

Swift 3.x KVO Solution (Updated @arango_86's answer)

Add Observer

self.addObserver(
    self, 
    forKeyPath: "<YOUR_VIEW>.bounds", 
    options: .new, 
    context: nil
)

Observe Values

override open func observeValue(
    forKeyPath keyPath: String?, 
    of object: Any?, 
    change: [NSKeyValueChangeKey : Any]?, 
    context: UnsafeMutableRawPointer?
) {
    if (keyPath == "<YOUR_VIEW.bounds") {
      updateDashedShapeLayerFrame()
      return
    }

    super.observeValue(
        forKeyPath: keyPath, 
        of: object, 
        change: change, 
        context: context
    )
}
查看更多
Emotional °昔
4楼-- · 2019-01-16 23:03

My solution when I create with dashed border

class DashedBorderView: UIView {

   let dashedBorder = CAShapeLayer()

   override init(frame: CGRect) {
       super.init(frame: frame)
       commonInit()
   }

   required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
       commonInit()
   }

   private func commonInit() {
       //custom initialization
       dashedBorder.strokeColor = UIColor.red.cgColor
       dashedBorder.lineDashPattern = [2, 2]
       dashedBorder.frame = self.bounds
       dashedBorder.fillColor = nil
       dashedBorder.cornerRadius = 2
       dashedBorder.path = UIBezierPath(rect: self.bounds).cgPath
       self.layer.addSublayer(dashedBorder)
   }

   override func layoutSublayers(of layer: CALayer) {
       super.layoutSublayers(of: layer)
       dashedBorder.path = UIBezierPath(rect: self.bounds).cgPath
       dashedBorder.frame = self.bounds
   }
}
查看更多
够拽才男人
5楼-- · 2019-01-16 23:08

I had a similar problem - needing to set the frame of a 'CALayer' when using auto layout with views (in code, not IB).

In my case, I had a slightly convoluted hierarchy, having a view controller within a view controller. I ended up at this SO question and looked into the approach of using viewDidLayoutSubviews. That didn't work. Just in case your situation is similar to my own, here's what I found...

Overview

I wanted to set the frame for the CAGradientLayer of a UIView that I was positioning as a subview within a UIViewController using auto layout constraints.

Call the subview gradientView and the view controller child_viewController.

child_viewController was a view controller I'd set up as a kind of re-usable component. So, the view of child_viewController was being composed into a parent view controller - call that parent_viewController.

When viewDidLayoutSubviews of child_viewController was called, the frame of gradientView was not yet set.

(At this point, I'd recommend sprinkling some NSLog statements around to get a feel for the sequence of creation of views in your hierarchy, etc.)

So I moved on to try using viewDidAppear. However, due to the nested nature of child_viewController I found viewDidAppear was not being called.

(See this SO question: viewWillAppear, viewDidAppear not being called, not firing).

My current solution

I've added viewDidAppear in parent_viewController and from there I'm calling viewDidAppear in child_viewController.

For the initial load I need viewDidAppear as it's not until this is called in child_viewController that all of the subviews have their frames set. I can then set the frame for the CAGradientLayer...

I've said that this is my current solution because I'm not particularly happy with it.

After initially setting the frame of the CAGradientLayer - that frame can become invalid if the layout changes - e.g. rotating the device.

To handle this I'm using viewDidLayoutSubviews in child_viewController - to keep the frame of the CAGradientLayer within gradientView, correct.

It works but doesn't feel good. (Is there a better way?)

查看更多
乱世女痞
6楼-- · 2019-01-16 23:09

I implemented the method layoutSubviews of my custom view; inside this method I just update each sublayer's frame to match the current boundaries of my subview's layer.

-(void)layoutSubviews{
      sublayer1.frame = self.layer.bounds;
}
查看更多
贼婆χ
7楼-- · 2019-01-16 23:12

According to this answer, layoutSubviews does not get called in all needed cases. I have found this delegate method more effective:

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self != nil) {
        [self.layer addSublayer:self.mySublayer];
    }
    return self;
}

- (void)layoutSublayersOfLayer:(CALayer*)layer
{
    self.mySublayer.frame = self.bounds;
}
查看更多
登录 后发表回答