创建哈希标记按钮

时间:2016-12-21 13:12:11

标签: ios objective-c swift

我有一个字符串,如下所示:#romantic #TLVLove #tagsforlikes #funday #telavivcity #summervacation(当然这个字符串是动态的,并且会一直改变。)

我想这样呈现:

Image

(每个标签的单独按钮,每个UIButton之间有一个空格。)

我知道如何将字符串分隔到其他字符串(在每个空格后)并创建具有该标题的UIButton,但我怎么知道按钮的大小和位置(原点)不会离开屏幕(如果标签没有足够的空间,则该行应该断开到另一条线。)

2 个答案:

答案 0 :(得分:3)

您可以使用UICollectionView自我调整单元格来完成,您需要做的是

<强>第一

选择 UICollectionView 并在 UICollectionViewCell 中按一个按钮,然后从所有 UIButton 设置约束 4面,即左,右,下,左边。

enter image description here

<强>第二

现在设置约束后,您可以在viewDidLoad中定义estimatedItemSize UICollectionView UICollectionViewFlowLayout这样的override func viewDidLoad() { super.viewDidLoad() let collectionViewFlowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout collectionViewFlowLayout.estimatedItemSize = CGSize(width: 34, height: 50) }

collectionView

此处IBOutletUICollectionView

let arrButtons = ["#B1","#ButtonButton2","#Bu3","#Buttontton11","#Buttodasfdsafasdn1","#Bu3","#Buttofn1","#Buttodasfdsafasdntodn11"]

<强>第三

对于我使用静态数组的按钮的名称,您可以从数据中将其视为动态

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! RPCollectionViewCell

    cell.btn.setTitle(arrButtons[indexPath.row], for: .normal)

    return cell
}

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

    return arrButtons.count

}

<强>四

之后,您只需要实现UICollectionView的数据源方法

{{1}}

,结果是

{{3}}

答案 1 :(得分:0)

let arrayOfStrings = hashTagString.componentSeparatedBy(" ");// This will give you an array of strings separated by space token.

现在您可以通过CollectionView创建按钮,在UIView上创建动态分配按钮,也可以使用您想要绘制的任何方法。 如果您仍然感到困惑,请参阅Rajat先生的回答,而不是将硬编码值分配给这样的数组,

let arrButtons = ["#B1","#ButtonButton2","#Bu3","#Buttontton11","#Buttodasfdsafasdn1","#Bu3","#Buttofn1","#Buttodasfdsafasdntodn11"];

通过将字符串拆分为数组来使用我正在创建的arrayOfString。

如果您想在按钮上绘制圆角边框,只需在return cell

之前添加这两行
cell.layer.cornerRadius = 4;
cell.layer.maskToBound = true
cell.layer.borderColor = UIColor.redColor()
cell.layer.borderWidth = 1