創建圖像
UIImage *image = [UIImage imageNamed:@"image"];
創建按鈕,並設置背景圖像和對象的行動。
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];
創建的UIView並添加按鈕子視圖
UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; [view addSubview:button];
與自定義視圖創建欄按鈕項目,將其設置爲導航欄右邊的項目
UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithCustomView:view]; self.navigationItem.rightBarButtonItem = actionButton;
注意: @ 2x圖像應該是雙倍大小。如果你的iamgeView是30x30,那麼你的圖像應該是60X60。如果你有30x30的圖像和名稱@ 2x,它將被用作15x15所以,使你的圖像的雙倍大小或使用它沒有@ 2x
提供了與我在我的OP中的代碼相同的結果 – user717452
替換action @ 2x .png與action.png –
這讓它感動了,但也讓它變得很小。 – user717452