我将一些自定义图像UIBarButtonItems添加到导航栏。如果我不搞乱item.width属性,则我的按钮太靠近,但是如果我用width属性将它们隔开,则按钮图像会失真。如何保持按钮图像的长宽比,但又保留自定义项目的空间?





    // Create custom map button
    UIButton *mapButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [mapButton setImage:[UIImage imageNamed:@"map.png"] forState:UIControlStateNormal];
    [mapButton addTarget:self action:@selector(dismissMapView:) forControlEvents:UIControlEventTouchUpInside];
    [mapButton setFrame:CGRectMake(280, 25, 30, 30)];
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithCustomView:mapButton];
    button1.width = (self.drawer.frame.size.width / 5.0f); // Space it out a bit

    // Create custom list button
    UIButton *listButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [listButton setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    [listButton addTarget:self action:@selector(scrollToRow:) forControlEvents:UIControlEventTouchUpInside];
    [listButton setFrame:CGRectMake(280, 25, 30, 30)];
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:listButton];
    button2.width = (self.drawer.frame.size.width / 5.0f); // Space it out a bit

    // Add buttons to drawer
    self.drawer.items = @[button1,button2];

最佳答案

尝试使用此代码在navigationbar中添加自定义栏按钮。

        UIImage* image3 = [UIImage imageNamed:@"compose_message_button.png"];
        CGRect frameimg = CGRectMake(250, 9, 43,32);
        UIButton *SettingButton = [[UIButton alloc] initWithFrame:frameimg];
        [SettingButton setBackgroundImage:image3 forState:UIControlStateNormal];
        [SettingButton addTarget:self action:@selector(BtnWriteMessage:)
                forControlEvents:UIControlEventTouchUpInside];
        [SettingButton setShowsTouchWhenHighlighted:YES];
        UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:SettingButton];
        self.navigationItem.rightBarButtonItem=mailbutton;
        [SettingButton release];


我希望这段代码对您有用。

09-11 18:16
查看更多