2014-11-21 43 views
0

我目前正在使用此示例代碼來產生一個ImageView下面有一個按鈕,它會產生一個日誌,當按下。如何創建一個總是直接在圖像下面的圖像的框架更改大小的按鈕

- (void)loadView { 
[super loadView]; 

imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SteveJobsMacbookAir.JPG"]]; 
[imageView setFrame:CGRectMake(80.0, 20.0, 160.0, 230.0)]; 
[imageView setContentMode:UIViewContentModeScaleAspectFit]; 

[[self view] addSubview:imageView]; 

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self action:@selector(cropImage) forControlEvents:UIControlEventTouchUpInside]; 
[button setFrame:CGRectMake(124.0, 258.0, 72.0, 37.0)]; 
[button setTitle:@"Crop!" forState:UIControlStateNormal]; 

[[self view] addSubview:button]; 
} 

當我按下「裁剪!」時按鈕,上面圖像的尺寸更改大小:

- (void)cropImage { 
[imageView setFrame:CGRectMake(80.0, 20.0, 160.0, 230.0)]; 
} 

但是,按鈕保持在同一個地方,而不是在圖像下方。我怎樣才能調整圖像的框架,同時讓按鈕再次移動到正下方?

+1

作爲一個適當的程序員請使用,並按照** **自動佈局,以實現像上面。設置按鈕和圖像視圖的垂直距離和它下面。 – Esha 2014-11-21 11:13:59

回答

0

只需將y按鈕的位置賦予相對於imageView的y位置的變量即可。 試試這個

[button setFrame:CGRectMake(124.0, imageView.frame.size.height + imageView.frame.origin.y + 20, 72.0, 37.0)]; 

+20爲您提供了ImageView的和按鍵之間的一些空間。 希望這有助於:)

+0

完美!對於將來閱讀此內容的人,每當上圖調整大小時,只需使用這一行代碼,並更新按鈕相對於它的位置。非常感謝Deepesh! :) – 2014-11-21 11:00:56

0

使用下面的代碼

- (void)loadView { 
[super loadView]; 

imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SteveJobsMacbookAir.JPG"]]; 
[imageView setFrame:CGRectMake(80.0, 20.0, 160.0, 230.0)]; 
[imageView setContentMode:UIViewContentModeScaleAspectFit]; 

[[self view] addSubview:imageView]; 

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
//Change bellow line 
[button addTarget:self action:@selector(cropImage:) forControlEvents:UIControlEventTouchUpInside]; 
[button setFrame:CGRectMake(124.0, 258.0, 72.0, 37.0)]; 
[button setTitle:@"Crop!" forState:UIControlStateNormal]; 

[[self view] addSubview:button]; 
} 
//Change to this function 
- (void)cropImage:(UIButton *)sender { 
[imageView setFrame:CGRectMake(80.0, 20.0, 160.0, 230.0)]; 
sender.center = CGPointMake(sender.center.x,imageView.center.y); 
}