问题
In the image below I am attempting to put a single-character label between each button, but as the second image shows, when I do insert the labels, the buttons disappear and (if you look closely) the last button's text moves to the right.
Can you help me get the desired result, please?
buttons without labels

buttons with labels

ViewController.h
@property(nonatomic,assign) UILabel* theSuit;
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString* cards = @"AKQJT98765432";
NSInteger yPipsOrigin = 100;
NSInteger xPipsOrigin = 100;
NSInteger xPipsStep = 40.0;
NSInteger xPipsCurrent = xPipsOrigin;
// Do any additional setup after loading the view.
for( int x=0;x<[cards length]; x++ ){
[cards substringWithRange:NSMakeRange(x,1)];
UIButton *b= [UIButton buttonWithType:UIButtonTypeRoundedRect];
xPipsCurrent += xPipsStep;
[b setTitle:[cards substringWithRange:NSMakeRange(x,1)] forState:UIControlStateNormal];
[b setTitle:@" " forState:UIControlStateDisabled];
[b setFrame:CGRectMake(xPipsCurrent, yPipsOrigin, 20, 20)];
[b setEnabled:YES];
[b setUserInteractionEnabled:YES];
[self.view addSubview:b];
[b addTarget:self action:@selector(spadeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
xPipsCurrent = xPipsOrigin + xPipsStep/2;
for( int x=0;x<[cards length]-1; x++ ){
xPipsCurrent += xPipsStep;
UILabel *lab = self.theSuit;
lab.text = @"Z";
lab.backgroundColor = [UIColor clearColor];
lab.center = CGPointMake(xPipsCurrent, yPipsOrigin);
[self.view addSubview:lab];
}
}
}
回答1:
NSString* cards = @"AKQJT98765432";
NSInteger yPipsOrigin = 100;
NSInteger xPipsOrigin = 100;
NSInteger xPipsStep = 40.0;
NSInteger xPipsCurrent = xPipsOrigin;
for( int x=0;x<[cards length]; x++ )
{
[cards substringWithRange:NSMakeRange(x,1)];
UIButton *b= [UIButton buttonWithType:UIButtonTypeRoundedRect];
xPipsCurrent += xPipsStep;
[b setTitle:[cards substringWithRange:NSMakeRange(x,1)] forState:UIControlStateNormal];
[b setTitle:@" " forState:UIControlStateDisabled];
[b setFrame:CGRectMake(xPipsCurrent, yPipsOrigin, 20, 20)];
[b setEnabled:YES];
[b setUserInteractionEnabled:YES];
[self.view addSubview:b];
[b addTarget:self action:@selector(spadeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(xPipsCurrent+b.frame.size.width, yPipsOrigin, 20, 20)];
lab.text = @"Z";
lab.textAlignment = NSTextAlignmentCenter;
lab.backgroundColor = [UIColor clearColor];
[self.view addSubview:lab];
}
来源:https://stackoverflow.com/questions/17167479/where-are-the-labels-among-the-buttons