开发者

UIScrollView addSubView: How do you prevent re-adding the same UILabel instance?

开发者 https://www.devze.com 2023-03-15 04:46 出处:网络
So apparently I\'m adding the same label over and over. I have an IBOutlet for UILabel that I hooked up in IB. I did that because that\'s the position I want it in for my UIScrollView. I also want a n

So apparently I'm adding the same label over and over. I have an IBOutlet for UILabel that I hooked up in IB. I did that because that's the position I want it in for my UIScrollView. I also want a new label on each page in my ScrollView but I can't figure out how to do it.

Any suggestions for how to accomplish this? Because I'm lost :-/

AnotherMadeUpViewController.h

#import <UIKit/UIKit.h>

@interface AnotherMadeUpViewController : UIViewController<UIScrollViewDelegate>
{

    IBOutlet UIPageControl *pageControl;
    IBOutlet UIScrollView *scroller;
    IBOutlet UILabel *label;
}

@property (nonatomic,retain)IBOutlet UIPageControl *pageControl;
@property (nonatomic,retain)IBOutlet UIScrollView *scroller;
@property (nonatomic,retain)IBOutlet UILabel *label;


-(IBAction)clickPageControl:(id)sender;

@end

AnotherMadeUpViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    scroller.delegate=self;
    scroller.pagingEnabled=YES;
    scroller.directionalLockEnabled=YES;
    scroller.showsHorizontalScrollIndicator=NO;
    scroller.showsVerticalScrollIndicator=NO;
    scroller.contentSize=CGSizeMake(pageControl.numberOfPages*scroller.frame.size.width, scroller.frame.size.height);
    CGFloat labelOriginX = label.frame.origin.x;
    CGFloat labelOriginY = label.frame.origin.y;
    CGFloat scrollWidth = 0;
    int pageNumber = 0;
    for (int i=0; i<3; i++)
    {
        CGRect rect = label.frame;
        rect.size.height = label.frame.size.height;
        rect.size.width = label.frame.size.width;
        rect.origin.x = labelOriginX + scrollWidth;
        rect.origin.y = labelOriginY;
        label.frame = rect;
        label.text = [NSString stringWithFormat:@"%d", pageNumber];
      开发者_如何学运维  label.textColor = [UIColor redColor];
        [scroller addSubview:label];
        pageNumber++;
        scrollWidth += scroller.frame.size.width;
    }
    pageControl.numberOfPages=3;
    pageControl.currentPage=0;
    [self.view addSubview:scroller];
}


You are re-adding the same UILabel instance over and over then, nothing happens other than changing the label's location (frame) in the scrollView's contentView. You'd have to add 8 copies of that label to the scrollView, each in a different frame. If you want to tile an image in the scrollView's background, try setting its backgroundColor to a pattern image created with +[UIColor colorWithPatternImage: ]

0

精彩评论

暂无评论...
验证码 换一张
取 消