在我的应用程序的一个 ViewController
中有一个 UITextView
。我想在文本末尾有一个“允许推送通知”按钮。但是由于按钮是静态的,TextView
中的文本是动态的,具体取决于显示宽度,因此在某些设备和方向上看起来真的很糟糕。
有人知道如何解决这个问题吗?是否有可能在 TextView
中插入一个按钮。或者我可以根据 TextView
内容高度对齐按钮吗?
问候, 大卫。
最佳答案
UITextView
是 UIScrollView
的子类,您可以利用它来为它添加 subview ,就像添加任何普通的 UIScrollView
一样,技巧是通过按钮+填充的高度来偏移 TextView 的文本容器。例如:
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)
这将为您提供以下输出:
希望这对您有所帮助!
关于ios - 在用 Swift 编写的 Xcode 中的 iOS 应用程序中的 UITextView 中,将 UIButton 放置在文本的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674139/