在 Objective-C 的 for 循环中创建一个 textview
Create a textview in a for loop in Objective-C
我正在从 mysql 数据库中检索数据并想在文本视图中显示它。因此,我为每条数据创建了一个 for 循环。问题是它只创建一个文本视图,因此只显示第一条检索到的数据。我的代码如下:
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
//NSLog(@"%lu", (unsigned long)[json count]);
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
NSIndexPath *indexPath;
NSDictionary *info = [json objectAtIndex:indexPath.row];
for (int i = 0; i < [json count]; i++)
{
//NSLog(@"%@", json);
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:@"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
}
}
json是一个数组,info是json中的一个字典。
您在 json 上循环五次但打印相同的信息。您需要:
int yPos = 0;
for (int i = 0; i < [json count]; i++)
{
//NSLog(@"%@", json);
info = [json objectAtIndex:i];
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:@"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
yPos += myTextView.frame.size.height;
myTextView.frame = CGRectMake(0, yPos, myTextView.frame.size.width, myTextView.frame.size.height);
}
我正在从 mysql 数据库中检索数据并想在文本视图中显示它。因此,我为每条数据创建了一个 for 循环。问题是它只创建一个文本视图,因此只显示第一条检索到的数据。我的代码如下:
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
//NSLog(@"%lu", (unsigned long)[json count]);
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
NSIndexPath *indexPath;
NSDictionary *info = [json objectAtIndex:indexPath.row];
for (int i = 0; i < [json count]; i++)
{
//NSLog(@"%@", json);
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:@"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
}
}
json是一个数组,info是json中的一个字典。
您在 json 上循环五次但打印相同的信息。您需要:
int yPos = 0;
for (int i = 0; i < [json count]; i++)
{
//NSLog(@"%@", json);
info = [json objectAtIndex:i];
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:@"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
yPos += myTextView.frame.size.height;
myTextView.frame = CGRectMake(0, yPos, myTextView.frame.size.width, myTextView.frame.size.height);
}