我如何动态调整UIScrollView
的高度?基本上我创建了一堆UILabels
(UILabel的确切数量是随机的),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];
}
答案 0 :(得分:2)
您需要保留一个变量,以便在创建标签时跟踪要添加的标签数量和设置内容大小的高度。请参阅以下调整后的代码:
-(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)];
答案 1 :(得分:0)
我同意@Kyle,但内容大小将随着标签的位置前进,以最后一个位置+最后一个高度结束。所以他的想法需要在那里进行一些调整。
另外,只是为了确认:@world peace - 您想要更改滚动条的框架,还是仅仅是内容大小? @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
}