首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建散列表按钮

创建散列表按钮
EN

Stack Overflow用户
提问于 2016-12-21 13:12:10
回答 2查看 768关注 0票数 2

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

我想把它呈现如下:

(在每个UIButton之间有一个空格的每个标记都有单独的按钮)。

我知道如何将字符串分离到其他字符串(在每个空空间之后),并创建一个带有该标题的UIButton,但如何知道按钮的大小以及不会离开屏幕的位置(原点)(如果没有足够的空间,则该行应该换行)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-21 13:54:43

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

First

取一个UICollectionView并在该UICollectionViewCell中接受一个按钮,并从左、右、下和左四个方面设置UIButton约束

第二

现在,在设置约束之后,您可以在viewDidLoad中定义UICollectionViewUICollectionViewFlowLayoutestimatedItemSize,如下所示

代码语言:javascript
复制
override func viewDidLoad() {
    super.viewDidLoad()

    let collectionViewFlowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    collectionViewFlowLayout.estimatedItemSize = CGSize(width: 34, height: 50)

}

collectionViewIBOutlet of my UICollectionView

第三代

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

代码语言:javascript
复制
let arrButtons = ["#B1","#ButtonButton2","#Bu3","#Buttontton11","#Buttodasfdsafasdn1","#Bu3","#Buttofn1","#Buttodasfdsafasdntodn11"]

第四

之后,只需实现UICollectionView的数据源方法即可

代码语言:javascript
复制
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

}

结果是

票数 3
EN

Stack Overflow用户

发布于 2016-12-21 14:02:44

代码语言:javascript
复制
let arrayOfStrings = hashTagString.componentSeparatedBy(" ");// This will give you an array of strings separated by space token.

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

代码语言:javascript
复制
let arrButtons = ["#B1","#ButtonButton2","#Bu3","#Buttontton11","#Buttodasfdsafasdn1","#Bu3","#Buttofn1","#Buttodasfdsafasdntodn11"];

只需使用我正在创建的arrayOfString,方法是将字符串拆分为数组。

如果您想在按钮上绘制圆角边框,只需在return cell之前添加这两行

代码语言:javascript
复制
cell.layer.cornerRadius = 4;
cell.layer.maskToBound = true
cell.layer.borderColor = UIColor.redColor()
cell.layer.borderWidth = 1
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41263592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档