用Swift實(shí)現(xiàn)表情發(fā)送

? ? ? 蘋果官方一直大力推行Swift,Swift的簡潔跟高新能得到不少人的青睞娱仔,貌似Swift將要成為ios開發(fā)的主流。那么Swift跟OC有何不同呢,或者你用OC實(shí)現(xiàn)過不少炫酷的功能墓塌,但那些功能,你能用Swift實(shí)現(xiàn)嗎奥额?答案是肯定的苫幢,只要你稍微努力一下,我覺得垫挨,你肯定可以做到韩肝。?

? ? ? 今天我分享一個(gè)Swift做的小案例,希望能給學(xué)習(xí)Swift帶來一點(diǎn)點(diǎn)九榔,一丟丟幫助哀峻。由于工作比較緊涡相,所以,這個(gè)案例我會(huì)分兩次發(fā)剩蟀。

? ? ? 首先創(chuàng)建一個(gè)Swift的項(xiàng)目催蝗,跟OC創(chuàng)建一樣,只要把下圖選為Swift即可

這里演示的純代碼的方式育特,所以我把Main.stourboard刪除了丙号,順帶要把Info.plist的Main刪除,如下圖:

要在AppDelegate.swift里面添加如下代碼:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

window = UIWindow(frame: UIScreen.mainScreen().bounds)

let rootViewController = ViewController()

window?.rootViewController = rootViewController

window?.makeKeyAndVisible()

return true

}

這樣就可以加載到ViewController了缰冤。因?yàn)槲覀兌际屈c(diǎn)聊天的導(dǎo)航欄跳出鍵盤犬缨,再點(diǎn)擊表情,發(fā)送表情的棉浸。所以遍尺,我們需要在view的最下面,添加一個(gè)toolBar涮拗。因?yàn)橹饕獙?shí)現(xiàn)表情發(fā)送乾戏,所以,我只建立了一個(gè)UIBarButton三热。然后點(diǎn)擊該UIBarButton鼓择,就可以彈出選擇表情的collectionCell,可以滑動(dòng)可以選擇【脱現(xiàn)在送上全部代碼呐能。只建立了三個(gè)文件:


ViewController的代碼如下:


import UIKit

class ViewController: UIViewController {

/// 懶加載一個(gè)文本輸入框

lazy var textView: UITextView = UITextView()

/// 模擬聊天,創(chuàng)建表情工具欄

lazy var toolBar: UIToolbar = UIToolbar()

/// 是否添加動(dòng)畫

var isShowAnimation: Bool = true

/// 表情鍵盤

lazy var emotionKeyboard: EmotionKeyboard = EmotionKeyboard(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.width,271))

/// 是否是自定義鍵盤

var isEmotionKeyboard: Bool = false

override func viewDidLoad() {

super.viewDidLoad()

view.backgroundColor = UIColor.whiteColor()

setUpUI()

//監(jiān)聽系統(tǒng)的鍵盤彈出

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)

}

deinit {

NSNotificationCenter.defaultCenter().removeObserver(self)

}

}

extension ViewController {

func setUpUI() {

setUpUIToolBar()

setUpTextView()

}

func setUpTextView() {

view.addSubview(textView)

textView.font = UIFont.systemFontOfSize(14)

textView.backgroundColor = UIColor.greenColor()

textView.delegate = self

textView.snp_makeConstraints { (make) -> Void in

make.top.equalTo(view).offset(20)

make.left.equalTo(view)

make.right.equalTo(view)

make.bottom.equalTo(toolBar.snp_top)

}

}

func setUpUIToolBar() {

view.addSubview(toolBar)

/// 創(chuàng)建表情按鈕

let button = UIButton()

button.setImage(UIImage(named: "smile_normal"), forState: .Normal)

button.setImage(UIImage(named: "smile_highlighted"), forState: .Highlighted)

/// 添加點(diǎn)擊事件

button.addTarget(self, action: "emotionKeyboard:", forControlEvents: .TouchUpInside)

// 不少新手會(huì)容易忽略這一步抑堡,少了它摆出,表情按鈕就不顯示了

button.sizeToFit()

let item = UIBarButtonItem(customView: button)

toolBar.items = [UIBarButtonItem]()

toolBar.items?.append(item)

toolBar.backgroundColor = UIColor.redColor()

toolBar.snp_makeConstraints { (make) -> Void in

make.height.equalTo(44)

make.bottom.equalTo(view)

make.left.equalTo(view)

make.right.equalTo(view)

}

}

}

extension ViewController: UITextViewDelegate {

}

/// 系統(tǒng)鍵盤彈出時(shí),讀取系統(tǒng)鍵盤的origin.y的值首妖,以便自定義的toolBar隨著系統(tǒng)彈起

extension ViewController {

@objc private func keyboardWillChanged(notification: NSNotification) {

if isShowAnimation == true {

//彈出鍵盤時(shí)偎漫,Y的偏移量

let keyboardOriginY = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue().origin.y

let duration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSTimeInterval

let offset = keyboardOriginY - view.bounds.size.height

toolBar.snp_updateConstraints(closure: { (make) -> Void in

make.bottom.equalTo(view).offset(offset)

})

UIView.animateWithDuration(duration, animations: { () -> Void in

self.view.layoutIfNeeded()

})

}

}

/// 實(shí)現(xiàn)表情按鈕的點(diǎn)擊事件,切換系統(tǒng)鍵盤跟自定義鍵盤

@objc private func emotionKeyboard(button: UIButton) {

// 收起系統(tǒng)鍵盤

isShowAnimation = false

textView.resignFirstResponder()

isShowAnimation = true

if isEmotionKeyboard == false {

textView.inputView = emotionKeyboard

isEmotionKeyboard = true

}else {

// 切換回系統(tǒng)鍵盤

textView.inputView = nil

isEmotionKeyboard = false

}

textView.becomeFirstResponder()

}

}

自定義的表情鍵盤EmotionKeyboard的代碼如下

import UIKit

private let cellIdentifier = "cellIdentifier"

let labelTag = 9527

private class EmotionCellLayout: UICollectionViewFlowLayout {

override func prepareLayout() {

super.prepareLayout()

minimumInteritemSpacing = 0

minimumLineSpacing = 0

scrollDirection = .Horizontal

itemSize = CGSizeMake(UIScreen.mainScreen().bounds.width, 234)

}

}

class EmotionKeyboard: UIView {

/// 懶加載存放表情的CollectionView

lazy var emotionCollectionView: UICollectionView = {

let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionCellLayout())

collectionView.delegate = self

collectionView.dataSource = self

collectionView.pagingEnabled = true

collectionView.showsHorizontalScrollIndicator = false

collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)

collectionView.bounces = false

return collectionView

}()

/// 懶加載跳轉(zhuǎn)表情類型的導(dǎo)航條

lazy var toolBar: EmotionToolBar = {

let toolBar = EmotionToolBar(frame: CGRectZero)

toolBar.toolBarDelegate = self

return toolBar

}()

override init(frame: CGRect) {

super.init(frame: frame)

setUpUI()

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

extension EmotionKeyboard {

func setUpUI() {

/// 添加有缆,設(shè)置象踊,自動(dòng)布局子控件

addSubview(emotionCollectionView)

addSubview(toolBar)

backgroundColor = UIColor.orangeColor()

emotionCollectionView.snp_makeConstraints { (make) -> Void in

make.left.equalTo(self)

make.right.equalTo(self)

make.top.equalTo(self)

make.height.equalTo(234)

//make.bottom.equalTo(self.snp_bottom).offset(-42)

}

toolBar.snp_makeConstraints { (make) -> Void in

make.top.equalTo(emotionCollectionView.snp_bottom)

make.left.equalTo(self)

make.right.equalTo(self)

make.height.equalTo(37)

// make.bottom.equalTo(self.snp_bottom).offset(-50)

}

print("=============\(self.bounds)")

}

}

extension EmotionKeyboard: UICollectionViewDataSource {

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

return 4

}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 4

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath)

cell.contentView.viewWithTag(labelTag)?.removeFromSuperview()

let titleLabel = UILabel(frame: CGRectMake(20,20,300,100))

titleLabel.tag = labelTag

titleLabel.text = "我是第\(indexPath.section)組\n我是第\(indexPath.item)行"

titleLabel.numberOfLines = 0

titleLabel.font = UIFont.systemFontOfSize(25)

titleLabel.textAlignment = .Left

titleLabel.textColor = UIColor.blackColor()

cell.contentView.addSubview(titleLabel)

cell.backgroundColor = self.randomColor()

return cell

}

}

extension EmotionKeyboard: UICollectionViewDelegate {

func scrollViewDidScroll(scrollView: UIScrollView) {

let offsetX = scrollView.contentOffset.x

var indexPath = NSIndexPath(forItem: 0, inSection: 0)

let cells = emotionCollectionView.visibleCells()

if cells.count > 1 {

//第一個(gè)cell

let firstCell = cells[0]

let firstCellIndex = emotionCollectionView.indexPathForCell(firstCell)

let firstCellOriginX = firstCell.frame.origin.x

let firstCellRegion = abs(offsetX - firstCellOriginX)

//第二個(gè)cell

let nextCell = cells[1]

let nextCellIndex = emotionCollectionView.indexPathForCell(nextCell)

let nextCellOriginX = nextCell.frame.origin.x

let nextCellRegion = abs(offsetX - nextCellOriginX)

//判斷那個(gè)cell顯示的區(qū)域大,就用那個(gè)cell的section

indexPath = (firstCellRegion > nextCellRegion ? nextCellIndex : firstCellIndex)!

toolBar.selectedIndex = indexPath.section

}

}

}

extension EmotionKeyboard: EmotionToolBarDelegate {

func changEmotionKeyboardType(buttonIndex: Int) {

let indexPath = NSIndexPath(forItem: 0, inSection: buttonIndex)

emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: false)

}

}

extension EmotionKeyboard {

func randomColor() -> UIColor {

let r = CGFloat(random() % 255)

let g = CGFloat(random() % 255)

let b = CGFloat(random() % 255)

let color = UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0)

return color

}

}

自定義的EmotionToolBar的代碼如下:

import UIKit

protocol EmotionToolBarDelegate: NSObjectProtocol {

func changEmotionKeyboardType(buttonIndex: Int)

}

class EmotionToolBar: UIStackView {

weak var toolBarDelegate: EmotionToolBarDelegate?

var selectedButton: UIButton?

var selectedIndex: Int = 0 {

didSet {

selectedButton?.selected = false

let button = viewWithTag(selectedIndex+labelTag) as! UIButton

button.selected = true

print(selectedIndex)

selectedButton = button

}

}

override init(frame: CGRect) {

super.init(frame: frame)

axis = .Horizontal

distribution = .FillEqually

setUpUI()

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

extension EmotionToolBar {

func setUpUI() {

///暫時(shí)先創(chuàng)建四個(gè)表情button

createToolBarButton("最近", tag: 0)

createToolBarButton("A號(hào)", tag: 1)

createToolBarButton("B號(hào)", tag: 2)

createToolBarButton("C號(hào)", tag: 3)

}

func createToolBarButton (title: String, tag: Int ) {

let button = UIButton()

button.setTitle(title, forState: .Normal)

button.backgroundImageForState(.Normal)

button.setTitleColor(UIColor.whiteColor(), forState: .Normal)

button.setTitleColor(UIColor.blackColor(), forState: .Selected)

button.addTarget(self, action: "changEmotionType:", forControlEvents: .TouchUpInside)

button.tag = tag+labelTag

addArrangedSubview(button)

if tag == 0? {

button.selected = true

selectedButton = button

}

}

}

extension EmotionToolBar {

@objc private func changEmotionType(button:UIButton) {

selectedButton?.selected = false

button.selected = true

selectedButton = button

toolBarDelegate?.changEmotionKeyboardType(button.tag-labelTag)

}

}

這樣實(shí)現(xiàn)表情欄的滾動(dòng)與選擇了棚壁。效果如下圖:


下一篇杯矩,會(huì)在collectionCell里面添加表情,后續(xù)表情的添加袖外,請(qǐng)留意后續(xù)更新史隆。

現(xiàn)在代碼里飽含了幾種屬性的定義,方法的創(chuàng)建曼验,分類的添加泌射,協(xié)議的定義头镊,方法的重寫與調(diào)用,基本數(shù)據(jù)類型魄幕,數(shù)組相艇,字典的定義,希望看客們好好理解一下纯陨。細(xì)心的看客們肯定已經(jīng)發(fā)現(xiàn)坛芽,代碼里有很多“?”與“翼抠!”咙轩,這里涉及到可選值的問題,會(huì)在后面作詳細(xì)的解析阴颖。

?最后 活喊,謝謝光臨。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末量愧,一起剝皮案震驚了整個(gè)濱河市钾菊,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌偎肃,老刑警劉巖煞烫,帶你破解...
    沈念sama閱讀 221,273評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異累颂,居然都是意外死亡滞详,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門紊馏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來料饥,“玉大人,你說我怎么就攤上這事朱监“斗龋” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵赌朋,是天一觀的道長凰狞。 經(jīng)常有香客問我篇裁,道長沛慢,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,520評(píng)論 1 296
  • 正文 為了忘掉前任达布,我火速辦了婚禮团甲,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘黍聂。我一直安慰自己躺苦,他們只是感情好身腻,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著匹厘,像睡著了一般嘀趟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上愈诚,一...
    開封第一講書人閱讀 52,158評(píng)論 1 308
  • 那天她按,我揣著相機(jī)與錄音,去河邊找鬼炕柔。 笑死酌泰,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的匕累。 我是一名探鬼主播陵刹,決...
    沈念sama閱讀 40,755評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼欢嘿!你這毒婦竟也來了衰琐?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,660評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤炼蹦,失蹤者是張志新(化名)和其女友劉穎碘耳,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體框弛,經(jīng)...
    沈念sama閱讀 46,203評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辛辨,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瑟枫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片斗搞。...
    茶點(diǎn)故事閱讀 40,427評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖慷妙,靈堂內(nèi)的尸體忽然破棺而出僻焚,到底是詐尸還是另有隱情,我是刑警寧澤膝擂,帶...
    沈念sama閱讀 36,122評(píng)論 5 349
  • 正文 年R本政府宣布虑啤,位于F島的核電站,受9級(jí)特大地震影響架馋,放射性物質(zhì)發(fā)生泄漏狞山。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評(píng)論 3 333
  • 文/蒙蒙 一叉寂、第九天 我趴在偏房一處隱蔽的房頂上張望萍启。 院中可真熱鬧,春花似錦、人聲如沸勘纯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽驳遵。三九已至淫奔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間堤结,已是汗流浹背搏讶。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留霍殴,地道東北人媒惕。 一個(gè)月前我還...
    沈念sama閱讀 48,808評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像来庭,于是被迫代替她去往敵國和親妒蔚。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容