【问题标题】:UIButton set image and titleUIButton 设置图片和标题
【发布时间】:2013-03-06 08:39:24
【问题描述】:

我用下面的代码加载的图片是在上边,下半边是按钮的标题,但是只有图片,这是为什么呢?有什么好的建议请告诉我们,谢谢

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 44)];

    [myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
    [myButton setImageEdgeInsets: UIEdgeInsetsMake(0,0,22,0)];

    [myButton setTitle:@"test" forState:UIControlStateNormal];
    [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,10,0,10)];

    [self.view addSubview:myButton];

【问题讨论】:

标签: ios uibutton


【解决方案1】:

你也可以通过这种方式达到这个效果..试试这个::

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 55)];
UIImage *img = [UIImage imageNamed:@"icon.png"];
UIImageView *imgVw = [[UIImageView alloc ] init];
imgVw.image  = img;
imgVw.frame = CGRectMake(myButton.frame.origin.x, myButton.frame.origin.y, myButton.frame.size.width, (myButton.frame.size.height-18));
[myButton setTitle:@"test" forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(34,10,0,10)];
[myButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imgVw];    
[self.view addSubview:myButton];

你的按钮方法

-(void) btnClick:(id)sender
{
    NSLog(@"working");
}

你也可以从你的逻辑中实现:: 这里我在你的逻辑中编辑了一些代码

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 40, 35)];
[myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0,(myButton.frame.size.width-52),17,0)];
[myButton setTitle:@"test" forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,(myButton.frame.size.width-78),0,22)];
[self.view addSubview:myButton];

但是,在这个逻辑中,您必须将图像大小调整为 23*23 像素。 UIEdgeInsetsMake的参数会根据你的图片大小而改变。

希望这会有所帮助。编码愉快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2012-07-21
    • 1970-01-01
    • 2014-07-10
    • 2015-08-06
    相关资源
    最近更新 更多