How can I use UITextField inside a CALayer?

五迷三道 提交于 2019-12-11 14:06:31

问题


I want to add a textfield inside a CALayer but I don't find a wait to do it.

Code:

-(void)drawInContext:(CGContextRef)ctx
{        
    NSLog(@"OK");
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(0,120, self.frame.size.width, 100)];
    [field setText:@"Test"];
    [self addSublayer:field.layer];
}

Any idea, suggestion, good pratices :) ?


回答1:


There is no way you will manage to put a UITextField, which is a subclass of UIView, as a child (sublayer) of a CALayer, which expects an object with a CALayer ancestor.

However you certainly can find the superview of the CALayer, which inherits UIView and put the UITextField at the good place for the time it is displayed, and set the CALayer as the delegate of the UITextField to keep the content synchronised as you type (see UITextFieldTextDidChangeNotification notification or -textFieldDidEndEditing: delegate method in UITextField).

Here is how it looks in Quartz Composer (using Cocoa, not Cocoa Touch)




回答2:


good pratices :) ?

In my opinion this is a bad practice. Layers are lower level than views and you shouldn't mix them like this. Doing so, as shown in this question, can have consequences/side effects that you didn't think of.

You should either go all higher level and skip the layer idea and just put the UITextView into a view or go all lower level and put a CATextLayer into a layer. Note that CATextLayer is only for drawing, not editing. If you need the behaviour of the UITextField including the ability to be the first responser (i.e. support keyboard input), then the better solution is to stick to views.


As a side note: the place where you are adding the view into the layer is very bad practice. Drawing methods such as drawInContext: and drawRect: should be used for drawing. These are methods that potentially could be called many, many times in which case you would end up with many, many views/layer being added on top of each other.



来源:https://stackoverflow.com/questions/11019768/how-can-i-use-uitextfield-inside-a-calayer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!