1

谁能告诉我为什么这段代码不起作用?

self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.backButton setImage:[UIImage imageNamed:@"back_arrow.png"]
                 forState:UIControlStateNormal];
self.backButton.contentMode = UIViewContentModeCenter;
[self.backButton addTarget:self
                    action:@selector(backButtonAction:)
          forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
[navigationItem setLeftBarButtonItem:backButtonItem animated:NO];
navigationItem.hidesBackButton = YES;

编辑:

上什么都没有出现leftBarButtonItem。那就是问题所在。

4

2 回答 2

2

这应该工作

CGRect rect = CGRectMake(10, 0, 30, 30);
self.backButton = [[UIButton alloc] initWithFrame:rect];
[self.backButton setImage:[UIImage imageNamed:@"back_arrow.png"]
                 forState:UIControlStateNormal];
self.backButton.contentMode = UIViewContentModeCenter;
[self.backButton addTarget:self
                    action:@selector(backButtonAction:)
          forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
self.navigationItem.leftBarButtonItem = backButtonItem;
self.navigationItem.hidesBackButton = YES;
于 2012-12-16T18:57:10.807 回答
2

从文档:

“在创建自定义按钮(即 UIButtonTypeCustom 类型的按钮)时,按钮的框架最初设置为 (0, 0, 0, 0)。在将按钮添加到界面之前,您应该将框架更新为更合适的值。”

因此,如果您在第 2 行设置框架,您应该会看到一些内容,例如:

self.backButton.frame = CGRectMake(0, 0, 40, 20);
于 2012-12-16T19:15:11.360 回答