How can I remove or hide a sublayer? - objective-c

-(IBAction)displayinfo:(id)sender
{
sublayer = [CALayer layer];
if (appear == NO)
{
appear = YES;
sublayer.contents=(id)[UIImage imageNamed:#"infoPalette.png"].CGImage;
sublayer.frame= CGRectMake(300,200,350,250);
[self.view.layer addSublayer:sublayer];
}
else
{
[sublayer removeFromSuperlayer];
}
}
This allows the layer to appear but I can't remove it or hide it upon clicking the same button.

Replace your existing code with this one
-(IBAction)displayinfo:(id)sender
{
if ( appear == NO)
{
sublayer = [CALayer layer];
appear = YES;
sublayer.contents=(id)[UIImage imageNamed:#"infoPalette.png"].CGImage;
sublayer.frame= CGRectMake(300,200,350,250);
[self.view.layer addSublayer:sublayer];
}
else
{
[sublayer removeFromSuperlayer];
}
}

In my case where I added multiple sublayers to my background imageView, I removed all of them using
for (int i = 0 ; i < [self.backgroundImageView.layer.sublayers count]; i++ ) {
[[self.backgroundImageView.layer.sublayers objectAtIndex:i] removeFromSuperlayer];
}
Note: I also iterated like this
for (CALayer *layer in self.backgroundImageView.layer.sublayers) {
[layer removeFromSuperlayer];
}
but this results in BadAccess, probably the reason that I added some CAGradientLayer to backgroundImageView.Layer. (it doesn't make much sense though).

You change the code to be
- (IBAction)displayinfo:(id)sender{
if (appear == NO){
sublayer = [CALayer layer];
appear = YES;
sublayer.contents=(id)[UIImage imageNamed:#"infoPalette.png"].CGImage;
sublayer.frame= CGRectMake(300,200,350,250);
[self.view.layer addSublayer:sublayer];
}
else {
[sublayer removeFromSuperlayer];
}}
Sorry!, repeated solution

Related

Apply and animate many constraints to outlet collection of uiviews

I have an outlet collection of labels. The labels are in stack views parented by a stack view. When the view loads I'd like to have each label fade in and move slightly to the right one after the other. I can apply the constraint in a loop to offset it. But only one will animate back to the final position.
-(void)viewDidLoad {
[super viewDidLoad];
for (UILabel *lbl in _constructionlabels) {
lbl.alpha = 0.0;
leadingCnst=[NSLayoutConstraint
constraintWithItem:lbl
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:[lbl superview]
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:-25];
[self.view addConstraint:leadingCnst];
}
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
leadingCnst.constant = 0;
[UIView animateWithDuration:0.33 delay:2 options:UIViewAnimationOptionCurveEaseOut animations:^{
for (UILabel *lbl in self->_constructionlabels) {
lbl.alpha = 1.0;
}
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
}];
}
How can I apply constraints to every needed label, and then animate all of them one after the other?
Keep references to each label constraint and start all animations at once, each with a delay.
// Declare array to hold references to constraints
NSMutableArray* _labelConstraints = [NSMutableArray array];
-(void) viewDidLoad {
[super viewDidLoad];
for (UILabel * lbl in _constructionlabels) {
lbl.alpha = 0.0;
NSLayoutConstraint* leadingCnst = [NSLayoutConstraint
constraintWithItem: lbl
attribute: NSLayoutAttributeLeading
relatedBy: NSLayoutRelationEqual
toItem: [lbl superview]
attribute: NSLayoutAttributeLeading
multiplier: 1.0
constant: -25
];
[self.view addConstraint: leadingCnst];
// Add constraint reference
[_labelConstraints addObject: #(leadingCnst)];
}
}
-(void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
for (i = 0; i < [_constructionlabels count]; i++) {
// Get label
Label* lbl = [_constructionlabels objectAtIndex:i];
// Get constraint
NSLayoutConstraint* labelConstraint = [_labelConstraints objectAtIndex:i];
// Animate
[UIView animateWithDuration: 0.33 delay: i options: UIViewAnimationOptionCurveEaseOut animations: ^ {
lbl.alpha = 1.0;
labelConstraint.constant = 0;
[self.view layoutIfNeeded];
}
completion: ^ (BOOL finished) {}
];
}
}
Note: This is just a proof of concept - you may want to refactor the code.
(It's been a while since I wrote ObjC, if you let me know any mistakes I'll correct them.)
You will need to put a recursive function to animate each label one by one without for loop. Add completion block in the animation.
func animate(_ label: UILabel, completion: #escaping () -> Void) {
UIView.animate(withDuration: 1, animations: {
// add animation here
}, completion: { _ in
completion()
})
}
let labelCollection = [UILabel]()
var index = 0
func startAnimation() {
animate(labelCollection[index], completion: {
if self.index < self.labelCollection.count - 1 {
self.index = self.index + 1
self.startAnimation()
}
})
}

Texts blinking in UITextView

Dose anybody know how to animate text blinking in UITextView?
Regarding to blinking animation, I would like to use couple of colour variations in NSArray,,,
This is my current methods for it:
- (void)startFontColorFlashing:(UITextView *)textView{
[UIView animateKeyframesWithDuration:2.0
delay:0.0
options:UIViewKeyframeAnimationOptionRepeat | UIViewKeyframeAnimationOptionCalculationModeCubic
animations:^{
NSLog(#"Font flash animation start");
NSArray *fontFlashColorsArr = #[[UIColor redColor], [UIColor blueColor]];
NSUInteger colorCount = [fontFlashColorsArr count];
for (NSUInteger i = 0; i < colorCount; i++) {
[UIView addKeyframeWithRelativeStartTime:i/(CGFloat)colorCount
relativeDuration:1/(CGFloat)colorCount
animations:^{
textView.textColor = fontFlashColorsArr[i];
}];
}
}
completion:^(BOOL finished){
NSLog(#"Finished the animation! %d", finished);
}];
}
It should works, but as soon as staring the animation it will be finished.
Please give me a good tip!
Cheers,
I experienced difficulty attempting to animate the text color changing, just like you did. I'm not sure if this is the best solution, but it works for what you are trying to do. Just add a way to stop changeTextColor from being called an infinite number of times, like a global variable, and this should do the trick
- (void)textViewDidBeginEditing:(UITextView *)textView {
[self changeTextColor:textView];
}
- (void)changeTextColor:(UITextView *)textView {
[self performSelector:#selector(changeTextColor:) withObject:textView afterDelay:0.3];
if (textView.textColor == [UIColor redColor]) {
textView.textColor = [UIColor blueColor];
} else {
textView.textColor = [UIColor redColor];
}
}
Here is some updated code to use multiple colors. This assumes self.count is a global variable that is handling the number of times to blink. This is probably best done in a subclass of UITextView if you are using more than one in the same controller.
- (NSArray *)colors {
return #[[UIColor redColor], [UIColor blueColor], [UIColor greenColor]];
}
- (void)changeTextColor:(UITextView *)textView {
if (self.count < 20) {
[self performSelector:#selector(changeTextColor:) withObject:textView afterDelay:0.3];
} else {
self.count = 0;
return;
}
NSInteger colorIndex = self.count % 3;
self.textView.textColor = self.colors[colorIndex];
self.count++;
}

Recognize a path of user gesture

I'm working on an app with 9 views on screen, and I want the users to connect the views in a way they want, and record their sequence as password.
But I don't know which gesture recognizer I should use.
Should I use CMUnistrokeGestureRecognizer or combination of several swipe gesture or anything else?
Thanks.
You could use a UIPanGestureRecognizer, something like:
CGFloat const kMargin = 10;
- (void)viewDidLoad
{
[super viewDidLoad];
// create a container view that all of our subviews for which we want to detect touches are:
CGFloat containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - kMargin * 2.0;
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(kMargin, kMargin, containerWidth, containerWidth)];
container.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:container];
// now create all of the subviews, specifying a tag for each; and
CGFloat cellWidth = (containerWidth - (4.0 * kMargin)) / 3.0;
for (NSInteger column = 0; column < 3; column++)
{
for (NSInteger row = 0; row < 3; row++)
{
UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(kMargin + column * (cellWidth + kMargin),
kMargin + row * (cellWidth + kMargin),
cellWidth, cellWidth)];
cell.tag = row * 3 + column;
cell.backgroundColor = [UIColor lightGrayColor];
[container addSubview:cell];
}
}
// finally, create the gesture recognizer
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:#selector(handlePan:)];
[container addGestureRecognizer:pan];
}
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
// an example of the sort of graphical flourish to give the
// some visual cue that their going over the subview in question
// was recognized
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
NSLog(#"We went over:");
for (UIView *subview in gesturedSubviews)
{
NSLog(#" %d", subview.tag);
}
// you might as well clean up your static variable when you're done
gesturedSubviews = nil;
}
}
Obviously, you would create your subviews any way you want, and keep track of them any way you want, but the idea is to have subviews with unique tag numbers, and the gesture recognizer would just see which order you go over them in a single gesture.
Even if I didn't capture precisely what you want, it at least shows you how you can use a pan gesture recognizer to track the movement of your finger from one subview to another.
Update:
If you wanted to draw a path on the screen as the user is signing in, you could create a CAShapeLayer with a UIBezierPath. I'll demonstrate that below, but as a caveat, I feel compelled to point out that this might not be a great security feature: Usually with password entry, you'll show the user enough so that they can confirm that they're doing what they want, but not enough so that someone can glance look over their shoulder and see what the whole password was. When entering a text password, usually iOS momentarily shows you the last key you hit, but quickly turns that into an asterisk so that, at no point, can you see the whole password. Hence my initial suggestion.
But if you really have your heart set on showing the user the path as they draw it, you could use something like the following. First, this requires Quartz 2D. Thus add the QuartzCore.framework to your project (see Linking to a Library or Framework). Second, import the QuartCore headers:
#import <QuartzCore/QuartzCore.h>
Third, replace the pan handler with something like:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:location];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:location];
shapeLayer.path = path.CGPath;
}
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields a path that the user draws as the gesture proceeds:
Rather than showing the path the user draws with each and every movement of the user's finger, maybe you just draw the lines between the center of the subviews, such as:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:subview.center];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:subview.center];
shapeLayer.path = path.CGPath;
}
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields something like:
You have all sorts of options, but hopefully you now have the building blocks so you can design your own solution.
Forgive me Rob, pure Plagiarism here :) Needed the same code in swift 3.0 :) so I translated this great little example you wrote into swift 3.0.
ViewController.swift
import UIKit
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
func handlePan(gesture: UIPanGestureRecognizer)
{
var gesturedSubviews : [UIView] = []
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == .began)
{
gesturedSubviews.removeAll()
}
let location = gesture.location(in: gesture.view)
for subview in (gesture.view?.subviews)! {
if (subview.frame.contains(location)) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state != .recognized)
{
print("We went over:");
for subview in gesturedSubviews {
print(" %d", (subview as AnyObject).tag);
}
// you might as well clean up your static variable when you're done
}
}
}
}
Update: Almost that is; I tried to translate the update too, but my translation missed something and didn't work, so I searched around SO and crafted a similar if slightly different final solution.
import UIKit
import QuartzCore
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
// Here's a Swift 3.0 version based on Rajesh Choudhary's answer:
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.fillColor = nil
line.lineWidth = 8
line.opacity = 0.5
line.strokeColor = UIColor.red.cgColor
layer.addSublayer(line)
}
var gesturedSubviews : [UIView] = []
var startX: CGFloat!
var startY: CGFloat!
var endX: CGFloat!
var endY: CGFloat!
func handlePan(gesture: UIPanGestureRecognizer) {
if (gesture.state == .began)
{
gesturedSubviews = [];
let location = gesture.location(in: gesture.view)
print("location \(location)")
startX = location.x
startY = location.y
}
if (gesture.state == .changed) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
endX = location.x
endY = location.y
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:endX, y:endY))
startX = endX
startY = endY
}
if (gesture.state == .ended) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:location.x, y:location.y))
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
let location = gesture.location(in: gesture.view)
print("location \(location)")
for subview in (gesture.view?.subviews)! {
if subview.frame.contains(location) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
subview.alpha = 1.0
}
}
}
}
}

UIScrollView with UIImageview and gestures using transitionFromView acting strange

I made a view which holds a UIScrollview:
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 65, 300, 188)];
//BackViews will hold the Back Image
BackViews = [[NSMutableArray alloc] init];
for (int i=0; i<BigPictures.count; i++) {
[BackViews addObject:[NSNull null]];
}
FrontViews = [[NSMutableArray alloc] initWithCapacity:BigPictures.count];
[self.pageControl setNumberOfPages:BigPictures.count];
Then I add several UIImageviews containing images:
//BigPictures holds objects of type UIImage
for (int i = 0; i < BigPictures.count; i++) {
UIImageView *ImageView = [[UIImageView alloc] initWithImage:[BigPictures objectAtIndex:i]];
ImageView.frame = [self.scrollView bounds];
[ImageView setFrame:CGRectMake(self.scrollView.frame.size.width * i, ImageView.frame.origin.y, ImageView.frame.size.width, ImageView.frame.size.height)];
//this saves the FrontView for later (flip)
[FrontViews insertObject:ImageView atIndex:i];
[self.scrollView addSubview:test];
}
// Detect Single Taps on ScrollView
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flip)];
[self.scrollView addGestureRecognizer:tap];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
Ok so far so good. Now the method which does the flipImage part:
- (void)flip {
int currentPage = self.pageControl.currentPage;
UIView *Back = nil;
if ([BackViews objectAtIndex:currentPage] == [NSNull null]) {
//CreateBackView is just creating an UIView with text in it.
Back = [self CreateBackView];
[BackViews replaceObjectAtIndex:currentPage withObject:Back];
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[BackViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];
} else {
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[FrontViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromRight completion:NULL];
[BackViews replaceObjectAtIndex:currentPage withObject:[NSNull null]];
}
[self.view addSubview:Back];
[self rebuildScrollView];
}
This is what rebuildScrollView does:
- (void)rebuildScrollView
{
for (UIView *subview in self.scrollView.subviews) {
[subview removeFromSuperview];
}
for (int i = 0; i < BigPictures.count; i++) {
if ([BackViews objectAtIndex:i] == [NSNull null]) {
[self.scrollView addSubview:[FrontViews objectAtIndex:i]];
} else {
[self.scrollView addSubview:[BackViews objectAtIndex:i]];
}
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
}
So the behavior is the following:
If I click on the first image (1 of 3 in scrollview) the effect is the way I want it, meaning the frontimage turns around and shows the empty (white) back with some text in the middle
If I click on the second image, the image turns but the back is completely empty showing the grey background of the window. If I scroll to the other images, the still show the front image (as expected)
Now I click on the third image and its the same as 1) great.
Current layout is now [BackView, Nothing, Backview)
Lets run that again. But now I click on the last image and its the same as 2) :(
Any ideas whats going wrong here?
EDIT: Some new findings. I doubled the amount of pictures and this is how Front and Backviews are placed (after flipping each one). P = Picture & B = Backview.
P_1(B_1) - actually the only correct one
P_2(empty - should be B_2)
P_3(B_2 - should be B_3)
P_4(empty - should be B_4)
P_5(B_3 - should be B_5)
P_6(empty - should be B_6)
Did a complete rebuild and now it works. Really strange because I used the exact same code.

UITextField rightView "WhileEditing" problem

I try to subclass UITextField as follows to implement custom rightView as a Clear button:
-(void) drawRect:(CGRect)rect
{
[self.layer setBackgroundColor:[[UIColor colorWithRed:20.0/255.0 green:20.0/255.0 blue:20.0/255.0 alpha:1] CGColor]];
[self.layer setCornerRadius:15.0];
UIImage *imgClear = [UIImage imageNamed:#"btnClear"];
CGSize iSize = [imgClear size];
UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, iSize.width, iSize.height)];
[clearButton setImage:imgClear forState:UIControlStateNormal];
[clearButton addTarget:self action:#selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
[self setRightViewMode:UITextFieldViewModeWhileEditing];
[self setRightView:clearButton];
[clearButton release];
}
but the Problem is: when the textfield just becomes focus, "clear"-button becomes visible too and after i begin to tap the keyboard it dissapears. Any ideas?
I meet the same problem, too. I guess this is an iOS bug, however, I tried to fix this problem by following implementations and it works fine for me. Hope this will help you.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
...
[self addTarget:self action:#selector(onEditing:) forControlEvents: UIControlEventEditingChanged]
...
}
-(void) onEditing:(id)sender {
if(![self.text isEqualToString:#""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
}
- (BOOL)becomeFirstResponder{
BOOL ret = YES ;
ret = [super becomeFirstResponder] ;
if( ret & ![self.text isEqualToString:#""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
return ret ;
}
- (BOOL)resignFirstResponder
{
BOOL ret = YES ;
ret = [super resignFirstResponder] ;
if( ret )
self.rightViewMode = UITextFieldViewModeNever;
return ret ;
}
- (void) clearText:(id)sender
{
self.text = #"";
self.rightViewMode = UITextFieldViewModeNever;
}
You shoud use : [self setRightViewMode:UITextFieldViewModeAlways];
Subclass UITextField and override -layoutSubviews.
- (void)layoutSubviews
{
[super layoutSubviews];
// HACK: There is an iOS bug where the right view is not displayed when there is text in the text field. Also, iOS adds and removes the rightView. This code adds the right view and uses hide-unhide instead.
UIView *rightView = [self rightView];
if (rightView != nil && [self clearButtonMode] == UITextFieldViewModeNever) {
BOOL showRightView;
BOOL isFirstResponder = [self isFirstResponder];
switch ([self rightViewMode]) {
case UITextFieldViewModeNever:
showRightView = FALSE;
break;
case UITextFieldViewModeWhileEditing:
showRightView = isFirstResponder;
break;
case UITextFieldViewModeUnlessEditing:
showRightView = !isFirstResponder;
break;
case UITextFieldViewModeAlways:
default:
showRightView = TRUE;
break;
}
showRightView = (showRightView && ![[self text] isEqualToString:#""]);
[rightView setFrame:[self rightViewRectForBounds:[self bounds]]];
[rightView setHidden:!showRightView];
[self addSubview:rightView];
}
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
UITextField *searchField = nil;
for (UIView *subview in controller.searchBar.subviews) {
DebugLog(#"%#",[subview description]);
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
UIImageView *clearIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ClearIcon.png"]];
searchField.rightView = clearIconView;
searchField.rightViewMode = UITextFieldViewModeAlways;
[clearIconView release];
break;
}
}
}
Simple code for solve this problem
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
textField.rightViewMode=UITextFieldViewModeAlways;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
textField.rightViewMode=UITextFieldViewModeNever;
return YES;
}
I have written an open source class, STAResizingTextField, that allows you to specify custom clear text field button images.