gpt4 book ai didi

iphone - 以编程方式将 UIButtons 和 UIImages 添加到 UIScrollview

转载 作者:行者123 更新时间:2023-12-03 20:00:20 26 4
gpt4 key购买 nike

我修改了Apple的Scrolling示例获取从 CoreData 对象引用的文件创建的一系列图像。我可以很好地添加图像,但我还想以编程方式向每个图像添加一个 UIButton 。图像的数量取决于CoreData对象的数量,所以我不能使用IB。

任何人都可以给我一些关于如何最好地实现这一点的帮助吗?

以下是从 CoreData 存储中获取图像的代码:

NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
Sentence *testSentence = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:i];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imageName = [[paths objectAtIndex:0] stringByAppendingPathComponent:[testSentence image]];
NSLog(@"imageName: %@", imageName);

UIImage *image = [[UIImage alloc] initWithContentsOfFile:imageName];
NSLog(@"image: %@", image);

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
NSLog(@"imageView: %@", imageView);

[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setBackgroundColor:[UIColor blackColor]];

// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView1 addSubview:imageView];

[image release];
[imageView release];
}

[self layoutScrollImages]; // now place the photos in serial layout within the scrollview

这是在 ScrollView 中放置图像的代码:

- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];

// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;

curXLoc += (kScrollObjWidth);
}
}

// set the content size so it can be scrollable
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}

最佳答案

不确定我是否理解您的问题。你就不能这样做吗?

...
imageView.frame = rect;
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = imageView.frame;
[aButton addTarget:self action:@selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:aButton];

关于iphone - 以编程方式将 UIButtons 和 UIImages 添加到 UIScrollview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4235102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com