Objective C UIButton with divider并在选中时更改textcolor

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Objective C UIButton with divider并在选中时更改textcolor相关的知识,希望对你有一定的参考价值。

我创建了一排UIButtons并添加了一周的日期和日期作为UILabel。我还创建了一个UIView选择器,当选择该按钮时,它将突出显示整个按钮。

现在我不知道如何在按钮之间添加分隔符或垂直线。而不是突出显示UIButton我希望在选择按钮时将text colour更改为蓝色。请帮忙

我创造了什么

what i have

我想要实现的目标

want to achieve

CGFloat HEIGHT_BTN = 55.0; //--- 10 pixels from the navigation view

CGFloat HEIGHT_LABEL = 30.0;
CGFloat HEIGHT_LABEL2 = 15.0;


   -(void)setupSegmentButtons
{
    CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;

//=== The view where the buttons sits
navigationView = [[UIView alloc]initWithFrame:CGRectMake(0,Y_POS_BTN,self.view.frame.size.width,HEIGHT_BTN)];
navigationView.backgroundColor = [UIColor whiteColor];

[self.view addSubview:navigationView]; //=== Create a View called navigationView

//==== Setup the shadows
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:self.navigationView.bounds];
self.navigationView.layer.masksToBounds = NO;
self.navigationView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
self.navigationView.layer.shadowOffset = CGSizeMake(5.0f, 5.0f);
self.navigationView.layer.shadowOpacity = 0.8f;
self.navigationView.layer.shadowPath = shadowPath.CGPath;

//=== Get the dates and formatting of the dates
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfThisWeek;
NSTimeInterval durationOfWeek;

[calendar rangeOfUnit:NSWeekCalendarUnit
            startDate:&beginningOfThisWeek
             interval:&durationOfWeek
              forDate:now];

NSDateComponents *comps = [calendar components:NSUIntegerMax fromDate:now];

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/YYYY"];
NSDateFormatter *datelblFormat = [[NSDateFormatter alloc] init];
[datelblFormat setDateFormat:@"dd"];
NSDateFormatter *daylblFormat= [[NSDateFormatter alloc] init];
[daylblFormat setDateFormat:@"EEE"];

//=== Loop 7 times to create the Buttons and the 2 lines Labels
for (int i = 0; i<numControllers; i++) {

    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i*(self.navigationView.frame.size.width/numControllers), 0, (self.navigationView.frame.size.width/numControllers),HEIGHT_BTN)];

    [navigationView addSubview:button]; //=== Put the buttons into the navigation View

    NSString *dateString = [dateFormatter stringFromDate:[calendar dateFromComponents:comps]];
    [dtDate addObject:dateString];

    NSString *lblDate = [datelblFormat stringFromDate:[calendar dateFromComponents:comps]];

    firstLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,5,self.view.frame.size.width/numControllers,HEIGHT_LABEL)];

    firstLineButton.text = lblDate;
    firstLineButton.font = [UIFont systemFontOfSize:20];
    firstLineButton.textColor = [UIColor whiteColor];
    firstLineButton.textAlignment=NSTextAlignmentCenter;
    [button addSubview:firstLineButton]; //=== Put the Date in the 1st line of the the button

    NSString *lblDay = [daylblFormat stringFromDate:[calendar dateFromComponents:comps]];

    UILabel *secondLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,28,self.view.frame.size.width/numControllers,HEIGHT_LABEL2)];
    secondLineButton.text = lblDay;
    secondLineButton.textColor = [UIColor whiteColor];
    secondLineButton.font = [UIFont boldSystemFontOfSize:11];
    secondLineButton.textAlignment=NSTextAlignmentCenter;
    [button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button

    button.tag = i; //--- IMPORTANT: if you make your own custom buttons, you have to tag them appropriately

    button.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];//%%% buttoncolors

    [button addTarget:self action:@selector(tapSegmentButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    ++comps.day;
}

[self setupSelector]; //=== The selection bar or highligthed area
}

//=== sets up the selection bar under the buttons or the highligted buttons on the navigation bar
-(void)setupSelector {

    //CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;
    selectionBar = [[UIView alloc]initWithFrame:CGRectMake(0, Y_BUFFER, (self.view.frame.size.width/numControllers),HEIGHT_BTN)];
    selectionBar.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6]; //%%% sbcolor
    //selectionBar.alpha = 0.8; //%%% sbalpha
    [navigationView addSubview:selectionBar];
}

//=== When the top button is tapped
#pragma mark Setup
 -(void)tapSegmentButtonAction:(UIButton *)button {

    sDtDate = dtDate[button.tag];

    [self LoadClasses];

    __weak typeof(self) weakSelf = self;
    [weakSelf updateCurrentPageIndex:button.tag];

    NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;

    selectionBar.frame = CGRectMake(xCoor, selectionBar.frame.origin.y, selectionBar.frame.size.width, selectionBar.frame.size.height);
}
答案

好吧,我更喜欢更优雅的方式来实现这一目标。

首先,创建一个UIButton子类(让我们说WeekdayButton),它将从NSDate生成一个属性标题并进行配置,以便它能够显示具有不同字体的多行标题。

WeekdayButton.h

#import <UIKit/UIKit.h>

@interface WeekdayButton : UIButton

@property (strong, nonatomic) NSDate *date;

@end

WeekdayButton.m

#import "WeekdayButton.h"

@implementation WeekdayButton

static NSDateFormatter *dayFormatter;
static NSDateFormatter *weekFormatter;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    [self setup];
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setup];
}

- (void)setup {
    self.titleLabel.numberOfLines = 2;
    self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];
}


- (void)setDate:(NSDate *)date {
    _date = date;

    NSAttributedString *normalTitle = [self generateNormalTitle];;
    NSAttributedString *selectedTitle = [self generateSelectedTitle];

    [self setAttributedTitle:normalTitle forState:UIControlStateNormal];
    [self setAttributedTitle:selectedTitle forState:UIControlStateSelected];
}

- (NSAttributedString *)generateNormalTitle {
    NSMutableAttributedString *result = [NSMutableAttributedString new];

    if (!dayFormatter) {
        dayFormatter = [NSDateFormatter new];
        dayFormatter.dateFormat = @"dd";
    }

    if (!weekFormatter) {
        weekFormatter = [NSDateFormatter new];
        weekFormatter.dateFormat = @"EEE";
    }

    NSString *day = [[dayFormatter stringFromDate:self.date] stringByAppendingString:@"
"];
    NSString *week = [weekFormatter stringFromDate:self.date];

    [result appendAttributedString:[[NSAttributedString alloc] initWithString:day
                                                                   attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}]];

    [result appendAttributedString:[[NSAttributedString alloc] initWithString:week
                                                                   attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11]}]];

    [result addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, result.length)];

    return result;
}

- (NSAttributedString *)generateSelectedTitle {
    NSMutableAttributedString *result = [[self generateNormalTitle] mutableCopy];
    [result addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, result.length)];
    return result;
}

@end

然后在你的ViewController中创建一个水平的UIStackView,生成7个WeekdayButton按钮并从今天开始传递NSDate对象。

ViewController.m

#import "ViewController.h"
#import "WeekdayButton.h"

@interface ViewController ()

@property (strong, nonatomic) UIStackView *stackView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupWeekDayButtons];
}

- (void)setupWeekDayButtons {

    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 55)];
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:containerView];

    containerView.layer.shadowRadius = 5;
    containerView.layer.shadowColor = [UIColor blackColor].CGColor;
    containerView.layer.shadowOpacity = 0.5;
    containerView.layer.shadowOffset = CGSizeMake(0, 5);

    self.stackView = [[UIStackView alloc] initWithFrame:containerView.bounds];
    self.stackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.stackView.axis = UILayoutConstraintAxisHorizontal;
    self.stackView.distribution = UIStackViewDistributionFill;
    self.stackView.spacing = 0;
    [containerView addSubview:self.stackView]; //Embeding stackview in a UIView cause UIStackView can't draw shadow.

    int numberOfDays = 7;
    for (int i = 0; i < numberOfDays; i++) {
        NSDate *date = [[NSDate date] dateByAddingTimeInterval:i * 24 * 3600];
        WeekdayButton *button = [WeekdayButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(weekDayTapped:) forControlEvents:UIControlEventTouchUpInside];
        button.date = date;
        button.translatesAutoresizingMaskIntoConstraints = NO;
        [self.stackView addArrangedSubview:button];
        [button.widthAnchor constraintEqualToAnchor:self.stackView.widthAnchor
                                         multiplier:1/(CGFloat)numberOfDays].active = YES;

        if (i != numberOfDays - 1) {
            UIView *separator = [UIView new];
            separator.translatesAutoresizingMaskIntoConstraints = NO;
            separator.backgroundColor = [UIColor whiteColor];
            [button addSubview:separator];

            [separator.widthAnchor constraintEqualToConstant:1].active = true;
            [separator.trailingAnchor constraintEqualToAnchor:button.trailingAnchor constant:0].active = YES;
            [separator.centerYAnchor constraintEqualToAnchor:button.centerYAnchor constant:0].active = YES;
            [separator.heightAnchor constraintEqualToAnchor:button.heightAnchor multiplier:1 constant:-20].active = YES;
        }
    }
}

- (void)weekDayTapped:(WeekdayButton *)sender {
    [self.stackView.arrangedSubviews makeObjectsPerformSelector:@selector(setSelected:) withObject:nil]; //Deselecting all buttons
    sender.selected = YES; 

    NSLog(@"Selected: %@", sender.date);
    //TODO: Do your logic after selection here
}

@end

结果如下:

enter image description here

另一答案

我在这里提供了堆栈视图和自动布局的强大功能

代码将受到限制,您可以在IB中定制几乎所有内容。 设置选定状态时,按钮的色调可能需要小心。

-(IBAction)selector:(id)sender{
    UIButton * button = (UIButton *)sender;
    [button setSelected:  !button.isSelected ];
 }

setting in IB

selected State

topstackview second stack view

使用这个想法,您可以更快,更安全地构建您的示例。

另一答案

对于:“如何在按钮之间添加分隔符或垂直线”: 在[button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button之后添加一个视图作为分隔符

if (i < (numControllers - 1)){  
    UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(button.frame.size.width - 1, 5, 1, button.frame.size.height - 10))];  
        separator.backgroundColor = UIColor.whiteColor
        [button addSubview:separator];  
}

对于文本颜色,请创建:btnCurrentSelected和:

@interface YouClass : UIViewController
{
    UIButton *btnCurrentSelected;
}




 -(void)tapSegmentButtonAction:(UIButton *)button {

    sDtDate = dtDate[button.tag];

    [self LoadClasses];
    [btnCurrentSelected setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] // set color for old button selected
    btnCurrentSelected = button
    [btnCurrentSelected setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] // set color for button selected

    __weak typeof(self) weakSelf = self;
    [weakSelf updateCurrentPageIndex:button.tag];

    NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;

    selection

以上是关于Objective C UIButton with divider并在选中时更改textcolor的主要内容,如果未能解决你的问题,请参考以下文章

Objective C - UIButton 保持突出显示/选中,背景颜色和字体颜色在突出显示/选中时发生变化

带有分隔线的Objective C UIButton并在选择时更改文本颜色

如何在 OBJECTIVE C 的 UITableViewCell 中更改先前按下的 UIButton 标签?

Objective c 动画 UIbutton 像 mac os x 上的停靠效果

将NSArray中的每个NSString元素显示为UIButton Objective C

将 NSArray 中的每个 NSString 元素显示为 UIButton Objective C