我创建了一行UIButtons
,并在其上添加了一周的日期和日期作为UILabel
。我还创建了一个UIView
选择所选择的按钮时,它会突出整个按钮。
现在,我被困在如何在按钮之间添加分隔符或垂直线的问题上。我不想突出显示UIButton
,而是希望在选择按钮时将text colour
更改为蓝色。请帮忙
我创造的
我正在努力实现的目标
代码
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
生成属性标题并进行配置,以便能够显示具有不同字体的多行标题。
#import <UIKit/UIKit.h>
@interface WeekdayButton : UIButton
@property (strong, nonatomic) NSDate *date;
@end
#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:@"\n"];
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
对象。#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
结果如下: