swift 第四课 随意 设置button 图片和文字 位置
生活随笔
收集整理的這篇文章主要介紹了
swift 第四课 随意 设置button 图片和文字 位置
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
項(xiàng)目中經(jīng)常遇到按鈕改變文字和圖片位置的情況,所以嘗試寫(xiě)一個(gè) button 的分類(lèi):
參照連接 http://blog.csdn.net/dfqin/article/details/37813591
import Foundation import UIKit/*
枚舉 設(shè)置 圖片的位置
*/ enum ButtonImagePosition : Int{case PositionTop = 0case Positionleftcase PositionBottomcase PositionRight }extension UIButton {
/**
imageName:圖片的名字
title:button 的名字
type :image 的位置
Space :圖片文字之間的間距
*/func setImageAndTitle(imageName:String,title:String,type:ButtonImagePosition,Space space:CGFloat) {self.setTitle(title, for: .normal)self.setImage(UIImage(named:imageName), for: .normal)let imageWith :CGFloat = (self.imageView?.frame.size.width)!;let imageHeight :CGFloat = (self.imageView?.frame.size.height)!;var labelWidth :CGFloat = 0.0;var labelHeight :CGFloat = 0.0;labelWidth = CGFloat(self.titleLabel!.intrinsicContentSize.width);labelHeight = CGFloat(self.titleLabel!.intrinsicContentSize.height);
var imageEdgeInsets :UIEdgeInsets = UIEdgeInsets();var labelEdgeInsets :UIEdgeInsets = UIEdgeInsets();switch type {case .PositionTop:imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - space/2.0, 0, 0, -labelWidth);labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);break;case .Positionleft:imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);break;case .PositionBottom:imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);break;case .PositionRight:imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0);break;}// 4. 賦值self.titleEdgeInsets = labelEdgeInsets;self.imageEdgeInsets = imageEdgeInsets;} }
調(diào)用方法:
/*使用方便 用xib 中建立的 leftBtn
*/
?
leftBtn.setImageAndTitle(imageName: "hezuojigou", title: "合作機(jī)構(gòu)", type: .PositionTop, Space: 0.0)
?
轉(zhuǎn)載于:https://www.cnblogs.com/Bob-blogs/p/6564971.html
總結(jié)
以上是生活随笔為你收集整理的swift 第四课 随意 设置button 图片和文字 位置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 基于粒子群优化算法的BP神经网络预测模型
- 下一篇: gcc对C语言的扩展:局部标签声明(Lo