在開發(fā)的過程中經(jīng)常會遇到需要在button中放置圖片和文字狱意,比如將圖片放置在button左邊,文字放置在右邊拯欧。因為UIButton也是繼承自UIView详囤,因此可以像其它的view一樣添加subView,
//創(chuàng)建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 創(chuàng)建imageview
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)];
[imageView setImage:image];
// 創(chuàng)建label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)];
[label setText:@"Your title"];
// 添加到button中
[button addSubview:label];
[button addSubview:imageView];
這種方法的好處是簡單明了镐作,但是其實在UIButton中已經(jīng)包含了UIImageView藏姐,我們不需要在自己添加該imageView的。也可以采用如下的方法该贾,但是該方法的在調整UI時比較不方便
cardNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[cardNameBtn setTitle:@"集卡名稱" forState:UIControlStateNormal];
//圖片
[cardNameBtn setImage:[UIImage imageNamed:@"card_flag_image"] forState:UIControlStateNormal];
//圖片基于文字的相對位置
cardNameBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
cardNameBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
//文字和圖片居中
cardNameBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[self addSubview:cardNameBtn];
還可以設置點擊時候的圖片改變
[self.forwardBtn setImage:[UIImage imageNamed:@"Forward_select.png"] forState:UIControlStateHighlighted];
[self.forwardBtn setTitleColor:RGBCOLOR(255, 160, 31) forState:UIControlStateHighlighted];
樣式如下:
209BB1F4-E4C1-45A0-AD6B-5799C6155B8F.png