在Xcode中更改按钮标签的位置

时间:2011-03-03 08:39:38

标签: iphone xcode button ios-4.2

我只是想知道是否有人可以帮我改变按钮标签的位置,这是我用代码制作的按钮。

非常感谢,

克里斯

3 个答案:

答案 0 :(得分:7)

如果您的意思是UIButton,请查看UIButton的titleEdgeInsets属性。

答案 1 :(得分:2)

所以按钮标签是UILabel的一个实例,不是吗?通过相对于UIButton框架设置框架来设置该标签的位置。

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button setFrame:CGRectMake(3, 20, w, h)];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, w, h)];
[titleLabel setText:@"TITLE"];
[button addSubview:titleLabel];
[self.view addSubview:button];
[titleLabel release];

我硬编码了按钮的x和y位置以及标签。您可以设置其他值,并将标签放在您想要的相应位置。

如果您只想设置该标签的文字位置,您可以这样做:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button setFrame:CGRectMake(3, 20, w, h)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, w, h)];
    [titleLabel setText:@"TITLE"];
    [titleLabel setTextAlignment:UITextAlignmentCenter];//(UITextAlignmentRight/UITextAlignmentLeft)
    [button addSubview:titleLabel];
    [self.view addSubview:button];
    [titleLabel release];

希望它会对你有所帮助。

答案 2 :(得分:0)

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0,0,50,32);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];

    [button addTarget:self action:@selector(BackBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 32)];
    backButtonView.bounds = CGRectOffset(backButtonView.bounds, -1, -4);
    [backButtonView addSubview:button];

    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
    //barButtonItem.imageInsets = UIEdgeInsetsMake(-6, 20, 30, 0);

    [self.navigationItem setLeftBarButtonItem:barButtonItem];
相关问题