专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
添加表情按钮
每页表情里面包含20个表情按钮和一个删除按钮.在HMEmoticonPageCell里面定义addEmoticonButtons来添加表情按钮, 并将添加的表情按钮放到emoticonButtons属性里面,方便在后面遍历所有的表情按钮// MARK: - 属性 /// 20个表情按钮数组 private lazy var emoticonButtons = [UIButton]() // /** 添加20个表情按钮到cell里面 */ private func addEmoticonButtons() { for _ in 0..<HMEmoticonNumberOfPage { // 创建按钮 let button = UIButton() button.backgroundColor = UIColor.random // 按钮添加到contentView contentView.addSubview(button) // 将按钮添加到数组,方便后面遍历按钮 emoticonButtons.append(button) } }- 在
setupUI里面调用addEmoticonButtons/// 准备UI private func setupUI() { addEmoticonButtons() contentView.addSubview(messageLabel) } 此时这些按钮没有
frame,并不能显示, 在layoutSubviews里面来重新设置这些按钮的位置定义常量
/// 每页显示20个表情按钮 let HMEmoticonNumberOfPage = 20 /// 每页显示7列 let HMEmoticonColumnOfPage = 7 /// 每页显示3行 let HMEmoticonRowOfPage = 3覆盖
layoutSubviews方法override func layoutSubviews() { super.layoutSubviews() layoutEmoticonButtons() }定义
layoutEmoticonButtons方法,重新布局按钮位置/// 重新布局按钮位置 private func layoutEmoticonButtons() { let margin: CGFloat = 5 let bottomMargin: CGFloat = 25 // 计算表情按钮的宽度与高度 let itemW = (frame.width - 2 * margin) / CGFloat(HMEmoticonColumnOfPage) let itemH = (frame.height - bottomMargin) / CGFloat(HMEmoticonRowOfPage) for i in 0..<emoticonButtons.count { let button = emoticonButtons[i] // 计算当前按钮是处于哪一行和哪一列 let column = i % HMEmoticonColumnOfPage let row = i / HMEmoticonColumnOfPage // 计算x和y值 let x = itemW * CGFloat(column) + margin let y = itemH * CGFloat(row) button.frame = CGRect(x: x, y: y, width: itemW, height: itemH) } }- 运行,效果如下
