我正在尝试为我的项目添加自定义栏按钮,但我遇到了一些问题。首先让我们回顾一下我的按钮的需求,它需要:
- to display a custom font
- to be enabled/disabled
- to have its colour animated based to provide user feedback.
所以我首先尝试通过故事板连接barButtonItem
,我可以更改颜色并启用禁用它。但是,我无法更改字体或添加颜色动画。我希望能够使用我在应用程序中使用的以下方法来设置颜色的动画:
- (void)textFlashTextfieldAnimation:(nonnull UITextField *)view duration:(NSTimeInterval)duration animateToColour:(UIColor*)animationColour textColor:(UIColor*)textColour completion:(void (^)(BOOL finished))completion {
[UIView transitionWithView:view duration:0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
view.textColor = animationColour;
} completion:^(BOOL finished) {
[UIView transitionWithView:view duration:2.0f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
view.textColor = textColour;
} completion:completion];
}];
}
理想情况下,我可以更改此功能以接受barButtonItem
/ UIButton
,以便我可以轻松制作动画。但是,如果我通过故事板连接按钮,则无法访问按钮的图层,因此无法进行动画。
我已经开始通过代码解决这个问题,但我已经走了两个死胡同。这是barButtonItem
的真正基本实现:
UIBarButtonItem *myButton=[[UIBarButtonItem alloc] initWithTitle:@"My Custom Button" style:UIBarButtonItemStylePlain target:self action:@selector(/*do something*/)];
[self.navigationItem setRightBarButtonItem:myButton];
现在这可以使用,我可以像故事板按钮一样使用它但是我不能改变字体或访问按钮的图层,所以它也不好。
然后,我尝试通过创建UIView
和UIButton
然后将其添加到barButtonItem
为我的栏按钮创建完全自定义视图,这可以在这里看到:
UIFont *barButtonFonts = [UIFont fontWithName:kFont size:16];
//Right Button
//create view
UIView *rightButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 45, 25)];
//create button
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
rightButton.backgroundColor = [UIColor clearColor];
rightButton.frame = rightButtonView.frame; //set frame = to view
[rightButton setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
rightButton.titleLabel.font = barButtonFonts;
rightButton.tintColor = [UIColor redColor];
[rightButton addTarget:self action:@selector(actionMethod) forControlEvents:UIControlEventTouchUpInside];
[rightButtonView addSubview:rightButton];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
self.navigationItem.rightBarButtonItem = rightBarButton;
现在我有一个显示自定义字体的barButtonItem
,但它根本没有UI交互。启用/禁用时以及未突出显示/突出显示时看起来相同。该按钮的工作原理应该是它应该看起来不应该。
我是否应该在代码中的某个位置创建此按钮的插座,以便在视图中更改按钮?是否可以在将按钮添加到导航栏后更改按钮?
如果有人有任何建议,我们将不胜感激!
答案 0 :(得分:1)
将barbuttonitem添加到栏中后,barbuttonitem是不可修改的。我能想到的唯一方法是删除按钮并在用户与其交互时添加一个新按钮(具有新特征)。我建议你使用自定义工具栏(就像普通的UIView),然后添加一个普通的按钮。它会更容易定制