UIScrollView addSubView:如何防止重新添加相同的UILabel实例?

时间:2011-06-25 17:33:59

标签: iphone uiscrollview addsubview

显然我一遍又一遍地添加相同的标签。我有一个UILabel的IBOutlet,我联系了IB。我这样做是因为这是我想要的UIScrollView的位置。我还想在我的ScrollView中的每个页面上都有一个新标签,但我无法弄清楚如何做到这一点。

有关如何完成此操作的任何建议?因为我输了: - /

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];
}

1 个答案:

答案 0 :(得分:1)

你一遍又一遍地重新添加相同的UILabel实例,除了在scrollView的contentView中更改标签的位置(框架)之外没有任何其他事情发生。您必须向scrollView添加该标签的8个副本,每个副本位于不同的框架中。如果要在scrollView的背景中平铺图像,请尝试将其backgroundColor设置为使用+[UIColor colorWithPatternImage: ]

创建的图案图像