首页 文章

UIButton文本和图像

提问于
浏览
3

我有一个UIButton . 在那UIButton我必须显示文字和图像 . 图像应在文本后显示 . 基于文本我想调整按钮框架 .
Button With Text n Image
查看图片 . 在文本"I am a Button"之后,我想添加像箭头一样的图像 .

UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *name = @"I am a button";
titleButton.titleLabel.text = [NSString stringWithFormat:@"%@", name];
titleButton.titleLabel.textColor = [UIColor whiteColor];
CGSize stringSize = [name sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"MyriadPro-Cond" size:24]}];
CGRect frame = CGRectMake(300, 30, stringSize.width, 30);
//frame.size.width = stringSize.width;
[titleButton setFrame:frame];
UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home.png"]];
image.frame = CGRectMake(stringSize.width, 14, 20, 13);
titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, stringSize.width+20, 0);
[titleButton addSubview:image];

我写了这样的代码 . 但它没有用 . 任何人都可以使它正确 . 提前致谢

1 回答

  • 0

    您不必在 UIButton 上添加 UIImageView 来获取此行为 . UIButton 本身有一些属性 . 将橙色图像设置为 buttonbackground image ,将箭头图像设置为 buttonimage . 然后调整 titleinsetsbuttonimage ,将 Headers 向左移动,箭头图像向右移动 .

    [btn setBackgroundImage:[UIImage imageNamed:@"orange_bg"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];
    
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -60, 0)];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 125, 0)];
    

    您必须根据图像和按钮大小调整插入 .

相关问题