将UIButton放在UptextView中的文本末尾,该应用程序位于用Swift编写的Xcode中的iOS应用程序中

在我的应用程序的一个ViewController中有一个UITextView 。 我希望在文本末尾有一个“允许推送通知”按钮。 但由于按钮是静态的,因此TextView的文本具有动态性,具体取决于显示宽度,在某些设备和方向上看起来非常糟糕。

有人知道如何解决这个问题吗? 是否有可能在TextView插入按钮。 或者我可以根据TextView内容高度对齐按钮吗?

问候,大卫。

来自UIScrollView UITextView子类,您可以像使用任何普通的UIScrollView一样使用它来向其添加子视图,其技巧是通过按钮+填充的高度来偏移文本视图的文本容器。 例如:

 let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 500)) textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae fermentum tellus. Donec dui sem, viverra eu auctor eleifend, aliquet id lorem. Nam id sapien sed arcu auctor commodo nec nec nulla. Praesent id mi nec odio consequat varius id sit amet quam." let buttonHeight: CGFloat = 44 let contentInset: CGFloat = 8 //inset the textView textView.textContainerInset = UIEdgeInsets(top: contentInset, left: contentInset, bottom: (buttonHeight+contentInset*2), right: contentInset) let button = UIButton(frame: CGRect(x: contentInset, y: textView.contentSize.height - buttonHeight - contentInset, width: textView.contentSize.width-contentInset*2, height: buttonHeight)) //setup your button here button.setTitle("BUTTON", forState: UIControlState.Normal) button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) button.backgroundColor = UIColor.lightGrayColor() //Add the button to the text view textView.addSubview(button) 

这将为您提供以下输出:

在此处输入图像描述

希望这可以帮助!