How to add barbutton programmatically with image

后端 未结 4 441
温柔的废话
温柔的废话 2021-01-24 11:47

I am creating a barbutton programmatically. But it can\'t fix into screen. Help me in solve this problem.

Screenshot:

4条回答
  •  悲&欢浪女
    2021-01-24 12:41

    I usually create the UIImageView, then a UITapGestureRecognizer and i add it to the UIImageView, and finally i create the UIBarbuttonItem:

        //UIImageView where the image is shown
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageName"]];
        imageViewSettings.frame = CGRectMake(0, 0, 25, 25);
        imageViewSettings.contentMode = UIViewContentModeScaleAspectFit;
    
        //TapGesture
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodToTrigger)];
    
        //Adding the gesture to the ImageView
        [imageView addGestureRecognizer:tapGesture];
    
        //Creating the barButtonItem
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
    
        //Finally add the button to the navigationBar
        self.navigationItem.rightBarButtonItem = barButtonItem;
    

提交回复
热议问题