我该如何动态调整UIScrollView的高度呢?基本上,我创建了一堆UILabels ( UILabels的确切数量是随机的),UIScrollView会自动调整其高度以适应UILables。这就是我到目前为止在viewDidLoad中所拥有的。
- (void)viewDidLoad
{
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320
, 1500)];
scroller.indicatorStyle = UIScrollViewIndicatorStyleWhite;
{ 这就是创建额外UILavels的操作
-(IBAction)scheduale{
int i;
for(i=0; i<[self retrieveTime] ; i++){
//Add time label
UILabel *timeLabel = [[UILabel alloc] init];
timeLabel.frame = CGRectMake(10, (i+1) * 21, 31, 20);
timeLabel.textColor = [UIColor whiteColor];
timeLabel.backgroundColor = [UIColor colorWithRed:76.0/225.0 green:76.0/225.0 blue:76.0/225.0 alpha:1.0];
NSString *labelString;
labelString = [[NSNumber numberWithInt:i] stringValue];
timeLabel.text = labelString;
timeLabel.textAlignment = UITextAlignmentCenter;
//theLabel.tag = (i+1) * 100;
[scroller addSubview:timeLabel];
}发布于 2012-04-05 10:26:04
您需要使用一个变量来跟踪要添加的标签数量及其高度,以便在完成创建标签时设置内容大小。请看下面调整后的代码:
-(IBAction)scheduale{
int i;
int contentSize = 0;
for(i=0; i<[self retrieveTime] ; i++){
UILabel *timeLabel = [[UILabel alloc] init];
timeLabel.frame = CGRectMake(10, (i+1) * 21, 31, 20);
contentSize += 20;
timeLabel.textColor = [UIColor whiteColor];
timeLabel.backgroundColor = [UIColor colorWithRed:76.0/225.0 green:76.0/225.0 blue:76.0/225.0 alpha:1.0];
NSString *labelString;
labelString = [[NSNumber numberWithInt:i] stringValue];
timeLabel.text = labelString;
timeLabel.textAlignment = UITextAlignmentCenter;
//theLabel.tag = (i+1) * 100;
[scroller addSubview:timeLabel]; }
[scroller setContentSize:CGSizeMake(320, contentSize)];发布于 2012-04-05 11:02:03
我同意@Kyle,但内容大小将随着标签的位置而前进,以最后一个位置+最后一个高度结束。因此,他的想法需要在这方面做一些调整。
另外,我只想确认一下:@world和平-你是想改变滚动条的边框,还是仅仅改变内容的大小?@Kyle是正确的,你至少必须改变内容的大小。
下面是对该代码的一些清理:
#define kButtonWidth 31.0
#define kButtonHeight 20.0
#define kMargin 1.0
-(IBAction)scheduale {
int i;
CGFloat contentPositionY = 0.0;
UIColor *labelColor = [UIColor colorWithRed:76.0/225.0 green:76.0/225.0 blue:76.0/225.0 alpha:1.0];
for(i=0; i<[self retrieveTime] ; i++){
//Add time label
UILabel *timeLabel = [[UILabel alloc] init];
timeLabel.frame = CGRectMake(0, contentPositionY, kButtonWidth, kButtonHeight);
contentPositionY += kButtonHeight + kMargin;
timeLabel.textColor = [UIColor whiteColor];
timeLabel.backgroundColor = labelColor;
timeLabel.text = [NSString stringWithFormat:@"@d", i];
timeLabel.textAlignment = UITextAlignmentCenter;
//theLabel.tag = (i+1) * 100;
[scroller addSubview:timeLabel];
}
// now size the content
scroller.contentSize = CGSizeMake(kButtonWidth, contentPositionY + kButtonHeight);
// and to get the margins you built into the loop calculation
scroller.contentInset = UIEdgeInsetsMake(21, 10, 0, 0); // your code implied these values
}https://stackoverflow.com/questions/10021799
复制相似问题