2

我想在我的應用程序中使用自己的圖像作爲操作按鈕。我的圖像大小爲30px X 30px。在我的應用程序中,我使用代碼:導航欄上的自定義UIBarButtonItem圖像偏移

UIBarButtonItem *heart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"[email protected]"] style:UIBarButtonItemStyleDone target:self action:@selector(theactionbutton)]; 
self.navigationItem.rightBarButtonItem = the action; 

但是,按鈕似乎離左側太遠。我附加了兩個圖像,第一個顯示原始動作按鈕,第二個顯示我的自定義圖像,用於比較。任何想法爲什麼它移動到左側?

enter image description here enter image description here

回答

-1
  1. 創建圖像

    UIImage *image = [UIImage imageNamed:@"image"];

  2. 創建按鈕,並設置背景圖像和對象的行動。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height); [button setBackgroundImage:image forState:UIControlStateNormal]; [button addTarget:self action:@selector(theactionbutton) forControlEvents:UIControlEventTouchUpInside];

  1. 創建的UIView並添加按鈕子視圖

    UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; [view addSubview:button];

  2. 與自定義視圖創建欄按鈕項目,將其設置爲導航欄右邊的項目

    UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithCustomView:view]; self.navigationItem.rightBarButtonItem = actionButton;

注意: @ 2x圖像應該是雙倍大小。如果你的iamgeView是30x30,那麼你的圖像應該是60X60。如果你有30x30的圖像和名稱@ 2x,它將被用作15x15所以,使你的圖像的雙倍大小或使用它沒有@ 2x

+0

提供了與我在我的OP中的代碼相同的結果 – user717452

+0

替換action @ 2x .png與action.png –

+0

這讓它感動了,但也讓它變得很小。 – user717452