Just My Life & My Work

[iOS] 按鈕中圖案位置

在按鈕中設定影像,影像預設位置為置中,那如果我想要偏左或偏右,該怎麼做呢?

iOS 按鈕中圖案位置-原始

我這裡要展示四個按鈕,按鈕圖案要聚集在中間,也就是最左邊和最右邊要擠的幅度最大~

NSInteger offset = 80;
		for (int i = 0; i < [imageArray count]; i++)
		{
			btn = [UIButton buttonWithType:UIButtonTypeCustom];
//			btn.showsTouchWhenHighlighted = YES;
			btn.tag = i;
if (i == 0) {
btn.frame = CGRectMake(width * i, 0, width + offset, frame.size.height);
btn.backgroundColor = [UIColor redColor];
//                btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 170, 0, 0);
}
else if (i == 1) {
btn.frame = CGRectMake(width * i + offset, 0, width - offset, frame.size.height);
btn.backgroundColor = [UIColor yellowColor];
}
else if (i == 2) {
btn.frame = CGRectMake(width * i, 0, width - offset, frame.size.height);
btn.backgroundColor = [UIColor greenColor];
}
else if (i == 3) {
btn.frame = CGRectMake(width * i - offset, 0, width + offset, frame.size.height);
btn.backgroundColor = [UIColor blueColor];
//                btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 170);
}
			[btn setImage:[imageArray objectAtIndex:i] forState:UIControlStateNormal];
			[btn setImage:[hightlightImageArray objectAtIndex:i] forState:UIControlStateHighlighted];
			[btn setImage:[hightlightImageArray objectAtIndex:i] forState:UIControlStateSelected];
			[btn addTarget:self action:@selector(tabBarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
btn.selected = NO;
btn.highlighted = NO;
			[self.buttons addObject:btn];
			[self addSubview:btn];
		}
}

分別測試contentHorizontalAlignmentimageEdgeInsets的效果~

iOS 按鈕中圖案位置-至左和至右

使用contentHorizontalAlignment。

iOS 按鈕中圖案位置-目標

使用imageEdgeInsets。

一些常用功能都已有API可直接拿來使用,所以盡量去挖掘和瞭解吧~如此可以節省由自己來寫的時間:)~

參考:UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲