2011-09-19 65 views
0

我有一個UIButton裏面有一個UIImageView。出於某種原因,該按鈕正在顯示在圖像的左側。這裏是我的代碼:UIImageView和UIButton沒有排隊

// Load resources 
for (int x = 0; x < [self.gameOptions.categories count]; x++) 
{ 
    Category* category = [self.gameOptions.categories objectAtIndex:x]; 
    UIButton* imageButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    NSMutableArray* imageArray = [NSMutableArray new]; 
    UIImageView* imageView = [[UIImageView alloc] init]; 

    for (int i = 0; i < [category.resources count]; i++) 
    { 
     Resource* resource = [category.resources objectAtIndex:i]; 

     [imageArray addObject:resource.targetImage]; 
    } 

    imageView.animationDuration = [imageArray count] * 2; 
    imageView.animationImages = imageArray; 
    int count = [self.categoryButtons count]; 
    imageView.frame = CGRectMake((count) * 50 + (count) * 10, 0, 50, 50); 
    [imageView startAnimating]; 

    imageButton.adjustsImageWhenHighlighted = NO; 
    imageButton.tag = category.categoryId; 
    [imageButton addTarget:self action:@selector(imageSelect:) forControlEvents:UIControlEventTouchUpInside]; 
    imageButton.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height); 
    DLog(NSStringFromCGPoint(imageButton.layer.frame.origin)); 
    DLog(NSStringFromCGPoint(imageView.frame.origin)); 
    DLog(NSStringFromCGPoint(imageButton.frame.origin)); 
    DLog(NSStringFromCGPoint(imageView.layer.frame.origin)); 
    [imageButton addSubview:imageView]; 


    [categorySelection setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)]; 
    [categorySelection addSubview:imageButton]; 
    [self.categoryButtons addObject:imageButton]; 
    [imageArray release]; 
    [imageView release]; 
} 

回答

1

每個視圖都有其子視圖的來源。

因此設置與ButtonView.frame.origin相同的ImageView.frame.origin不會將它們放在與superview完全相同的位置。

所以你的imageView需要將原點設置爲相對於按鈕左上角的值。

imageButton.frame = CGRect(20.0, 20.0, 100.0, 100.0); 
//then say you want the image to in the top left corner of the button 
imageView.frame = CGRect(0.0, 0.0, 50.0, 50.0); 
[imageButton addSubview:imageView]; 
+0

啊!我不知道這是一個相對的位置。很高興知道。 – user472292